头文件:
编译:添加 -lpthread 选项
示例:gcc -lpthread code.c -o a.out
#include#include #include #include #include #include #include unsigned int number = 0; void* thread1(void* para); //线程1服务函数 void* thread2(void* para); //线程2服务函数 int main(int argc, char** argv) { pthread_t threadID1, threadID2; int ret = 0; ret = pthread_create(&threadID1, NULL, thread1, NULL); //创建线程1 if(ret) { printf("Thread1 create failed!n"); exit(EXIT_FAILURE); } ret = pthread_create(&threadID2, NULL, thread2, NULL); //创建线程2 if(ret) { printf("Thread2 create failed!n"); exit(EXIT_FAILURE); } pthread_join(threadID1, NULL); //等待线程thread1结束 pthread_join(threadID2, NULL); //等待线程thread2结束 ptherad_exit((void*)0); //退出现场main return 0; } void* thread1(void* para) { printf("Function thread1 running...n"); while(1) { number = 100; sleep(1); printf("number: %un", number); } pthread_exit((void*)0); } void* thread2(void* para) { unsigned int count = 0; printf("Function thread2 running...n"); while(1) { count++; number = count; } pthread_exit((void*)0); }
结果分析:没有二元信号量的约束,线程thread1对number的赋值几乎不会等于100,原因是线程thread2对number的访问导致的。
#include#include #include #include #include #include #include unsigned int number = 0; sem_t semID; void* thread1(void* para); void* thread2(void* para); int main(int argc, char** argv) { pthread_t threadID1, threadID2; int ret = 0; ret = pthread_create(&threadID1, NULL, thread1, NULL); if(ret) { printf("Thread1 create failed!n"); exit(EXIT_FAILURE); } ret = pthread_create(&threadID2, NULL, thread2, NULL); if(ret) { printf("Thread2 create failed!n"); exit(EXIT_FAILURE); } ret = sem_init(&semID, 0, 1); if(ret == -1) { printf("Sem create failed!n"); exit(EXIT_FAILURE); } pthread_join(threadID1, NULL); pthread_join(threadID2, NULL); ptherad_exit((void*)0); return 0; } void* thread1(void* para) { printf("Function thread1 running...n"); while(1) { sem_wait(&semID); //等待信号量 number = 100; sleep(1); printf("number: %un", number); sem_post(&semID); //释放信号量 } pthread_exit((void*)0); } void* thread2(void* para) { unsigned int count = 0; printf("Function thread2 running...n"); while(1) { sem_wait(&semID); count++; number = count; sem_post(&semID); } pthread_exit((void*)0); }
结果分析:加入信号量后,不管是线程thread1还是线程thread2对number的访问都不能同时进行,对全局变量number进行了很好的保护。



