Created
December 11, 2012 20:30
-
-
Save tausen/4261887 to your computer and use it in GitHub Desktop.
Revisions
-
tausen created this gist
Dec 11, 2012 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> sem_t semaphore; void threadfunc() { while (1) { sem_wait(&semaphore); printf("Hello from da thread!\n"); sem_post(&semaphore); sleep(1); } } int main(void) { // initialize semaphore, only to be used with threads in this process, set value to 1 sem_init(&semaphore, 0, 1); pthread_t *mythread; mythread = (pthread_t *)malloc(sizeof(*mythread)); // start the thread printf("Starting thread, semaphore is unlocked.\n"); pthread_create(mythread, NULL, (void*)threadfunc, NULL); getchar(); sem_wait(&semaphore); printf("Semaphore locked.\n"); // do stuff with whatever is shared between threads getchar(); printf("Semaphore unlocked.\n"); sem_post(&semaphore); getchar(); return 0; }