使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果

前端之家收集整理的这篇文章主要介绍了使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个简单的程序解决读者作家问题使用信号量.它在 Linux操作系统上运行完美,但是当我在Mac OSX上运行它时,我会得到意想不到的结果,我不知道为什么.

我的计划:

  1. #include <semaphore.h>
  2. #include <sys/types.h>
  3. #include <stdio.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6.  
  7. void* function1(void* val);
  8. void* function2(void* val);
  9.  
  10. // shared values
  11. volatile int X;
  12. volatile int Y;
  13.  
  14. // declare semaphores
  15. sem_t s1;
  16. sem_t s2;
  17.  
  18. main()
  19. {
  20. void* status;
  21.  
  22. pthread_t thread1;
  23. pthread_t thread2;
  24. srand(time(NULL));
  25.  
  26. // initialize semaphores to zero
  27. sem_init(&s1,0);
  28. sem_init(&s2,0);
  29.  
  30. pthread_create(&thread1,NULL,function1,NULL);
  31. pthread_create(&thread2,function2,NULL);
  32.  
  33. pthread_join(thread1,&status);
  34. pthread_join(thread2,&status);
  35.  
  36. sem_destroy(&s1);
  37. sem_destroy(&s2);
  38.  
  39. }
  40.  
  41. void* function1(void* val)
  42. {
  43. while(1)
  44. {
  45. X = rand()%1000; // write
  46. printf("After thread ID A writes to X,X = %d\n",X);
  47. sem_post(&s1); // signal
  48. sem_wait(&s2); // wait
  49. printf("After thread ID A reads from Y,Y = %d\n",Y); // read
  50. sleep(3);
  51. }
  52. }
  53.  
  54. void* function2(void* val)
  55. {
  56. while(1)
  57. {
  58. sem_wait(&s1); // wait
  59. printf("After thread ID B reads from X,X); // read
  60. Y = rand()%1000; // write
  61. printf("After thread ID B write to Y,Y);
  62. sem_post(&s2); // signal
  63. sleep(3);
  64. }
  65. }

我在Linux上收到的输出(应该是什么样的):

  1. After thread ID A writes to X,X = 100
  2. After thread ID B reads from X,X = 100
  3. After thread ID B write to Y,Y = 234
  4. After thread ID A reads from Y,Y = 234
  5. ...

Mac OSX上的输出(意外):

  1. After thread ID A writes to X,X = 253
  2. After thread ID A reads from Y,Y = 0
  3. After thread ID B reads from X,X = 253
  4. After thread ID B write to Y,Y = 728
  5. ...

解决方法

检查sem_init调用错误返回;我敢打赌你会发现OS X版本返回一个“功能未实现”的错误.

这是因为unnamed POSIX semaphores are not implemented on OS X.您需要使用命名信号量,或pthread互斥体/条件变量.

猜你在找的Linux相关文章