linuc 執行緒間同步semaphore
阿新 • • 發佈:2019-02-19
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/stat.h> #include <fcntl.h> #include <semaphore.h> #include <unistd.h> union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; void *childThread(void* args); int value; int rc = 0; sem_t test_semaphore; int main(void) { int i = 0; sem_init(&test_semaphore, 1, 0); sem_getvalue(&test_semaphore, &value); printf("The value of semaphore is %d\n", value); pthread_t tid; pthread_create(&tid,NULL,childThread,NULL); while (i < 5) { sem_post(&test_semaphore); sem_getvalue(&test_semaphore, &value); i++; sleep(1); } return 0; } void *childThread(void* args){ while(1){ sem_wait(&test_semaphore); printf("I am the child thread. \n"); } }
上面就是一個簡單的執行緒間同步操作。