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

前端之家收集整理的这篇文章主要介绍了使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个简单的程序解决读者作家问题使用信号量.它在 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
...

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
...

解决方法

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

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

猜你在找的Linux相关文章