C/Semaphore
From Attie's Wiki
(Redirected from Semaphore)
Very brief show-how for semaphores on linux. Please note, that there isn't sufficient thread handling code here, just the minimum to make a thread run.
Compile with: gcc main.c -lpthread -o main
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> void *myThread(void *p) { sem_t *sem = p; printf("Thread started!\n"); sleep(5); printf("Poking semaphore\n"); sem_post(sem); return NULL; } int main(int argc, char *argv[]) { sem_t sem; pthread_t tid; sem_init(&sem, 0, 0); printf("Creating thread...\n"); pthread_create(&tid, NULL, myThread, (void*)&sem); printf("Waiting on thread...\n"); sem_wait(&sem); printf("Tidying up!\n"); sem_destroy(&sem); return 0; }