gpt4 book ai didi

c - Unix 信号量问题

转载 作者:行者123 更新时间:2023-12-02 03:42:01 26 4
gpt4 key购买 nike

我一直在为一个更大的学校项目编写有关线程同步的测试程序。我编写的测试程序之一是一小段代码,用于测试“semaphore.h”库。代码如下:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

//Semaphore
sem_t mutex;

//Critical section variable
int crit;

//Method for pthreads
void* method()
{
int x;

//Loop to increment 'crit'
for (x = 0; x < 5000000; x++)
{
sem_wait(&mutex);
//Critical Section
crit++;
sem_post(&mutex);
}

pthread_exit(0);
}

int main()
{
pthread_t t1, t2;

sem_init(&mutex, 0, 1);
pthread_create(&t1, NULL, method, NULL);
pthread_create(&t2, NULL, method, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&mutex);

//This value should be '10000000'
printf("Value of 'crit': %d\n", crit);

return 0;
}

“暴击”变量的最终值应该是一千万,但我只得到接近它的数字,表明存在竞争条件。我将我的代码与其他示例进行了比较,看起来不错,但我一直遇到同样的问题。有什么想法吗?

最佳答案

你的关键部分根本没有被锁定,这个假设很符合你的症状。

sem_init() 因 ENOSYS 而失败。 sem_wait()sem_post() 随后因 EINVAL 而失败,sem_destroy() 也失败(可能再次因 ENOSYS 而失败)。您的工作线程正在相互踩踏彼此的增量。

您使用的是 OS X 吗?这是目前最常见的不支持未命名 POSIX 信号量的平台。试试 named semaphore interface ,在同一个头文件中定义, 受支持。

关于c - Unix 信号量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com