大佬教程收集整理的这篇文章主要介绍了使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的计划:
#include <semaphore.h> #include <sys/types.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> void* function1(void* val); void* function2(void* val); // shared values volatilE int X; volatilE int Y; // declare semaphores sem_t s1; sem_t s2; main() { void* status; pthread_t thread1; pthread_t thread2; srand(time(NULL)); // initialize semaphores to zero sem_init(&s1,0); sem_init(&s2,0); pthread_create(&thread1,NULL,function1,null); pthread_create(&thread2,function2,null); pthread_join(thread1,&status); pthread_join(thread2,&status); sem_destroy(&s1); sem_destroy(&s2); } void* function1(void* val) { while(1) { X = rand()%1000; // write printf("After thread ID A writes to X,X = %d\n",X); sem_post(&s1); // signal sem_wait(&s2); // wait printf("After thread ID A reads from Y,Y = %d\n",Y); // read sleep(3); } } void* function2(void* val) { while(1) { sem_wait(&s1); // wait printf("After thread ID B reads from X,X); // read Y = rand()%1000; // write printf("After thread ID B write to Y,Y); sem_post(&s2); // signal sleep(3); } }
我在Linux上收到的输出(应该是什么样的):
After thread ID A writes to X,X = 100 After thread ID B reads from X,X = 100 After thread ID B write to Y,Y = 234 After thread ID A reads from Y,Y = 234 ...@H_588_16@mac OSX上的输出(意外):
After thread ID A writes to X,X = 253 After thread ID A reads from Y,Y = 0 After thread ID B reads from X,X = 253 After thread ID B write to Y,Y = 728 ...
以上是大佬教程为你收集整理的使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果全部内容,希望文章能够帮你解决使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。