mac可以写linux的进程,使用信号量的程序在Linux上运行正常… Mac OSX上的意外结果...

我写了一个简单的程序解决读者作家问题使用信号量.它在

Linux操作系统上运行完美,但是当我在Mac OSX上运行它时,我会得到意想不到的结果,我不知道为什么.

我的计划:

#include

#include

#include

#include

#include

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

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值