c - 使用信号量的程序在 Linux 上运行良好...在 Mac osX 上出现意外结果

标签 c macos synchronization semaphore

我编写了一个简单的程序来解决使用信号量的读者-作者问题。它在 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, 0);
sem_init(&s2, 0, 0);

pthread_create(&thread1, NULL, function1, NULL);
pthread_create(&thread2, NULL, 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 = %d\n", X); // read
    Y = rand()%1000; // write
    printf("After thread ID B write to Y, Y = %d\n", 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 互斥/条件变量。

关于c - 使用信号量的程序在 Linux 上运行良好...在 Mac osX 上出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4136181/

相关文章:

c# - 从 c char* 到 string/IntPtr c# 的转换

macos - python ffmpeg无法保存gif,但可以保存mp4

python - 为什么python 2.7.2在/usr/lib/python2.7中没有符号链接(symbolic link)

git - Subgit - 停止属性同步

Android Google DriveFile 元数据被缓存,而不是从云端获取

c - 如何将 sscanf 用于带空格的字符串?

c - 让 fftw.h 在 C 中工作

c - 如何编译 ratts - macOS 上的纯 C 语言语音合成库

eclipse - mac eclipse中运行java应用程序的快捷方式是什么

java - 事件调度线程内的同步问题