C/Semaphore
From Attie's Wiki
(Difference between revisions)
(Created page with "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. <source lang="c"> #inc...") |
m |
||
Line 2: | Line 2: | ||
Please note, that there isn't sufficient thread handling code here, just the minimum to make a thread run. | Please note, that there isn't sufficient thread handling code here, just the minimum to make a thread run. | ||
+ | Compile with: <code>gcc main.c -lpthread -o main</code> | ||
<source lang="c"> | <source lang="c"> | ||
#include <stdio.h> | #include <stdio.h> |
Revision as of 12:42, 19 November 2012
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; }