3

我一直在为一个更大的学校项目编写有关线程同步的测试程序。我编写的一个测试程序是一小段代码来测试“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;
}

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

4

1 回答 1

1

您的关键部分根本没有锁定,哪个假设非常适合您的症状。

sem_init()ENOSYS 失败。 sem_wait()随后sem_post()因 EINVAL 失败,并且也sem_destroy()失败(可能再次使用 ENOSYS)。您的工作线程正在踩着彼此的增量。

你在 OS X 上吗?这是目前最常见的平台,不支持未命名的 POSIX 信号量。尝试在同一个头文件中定义的命名信号量接口,这受支持的。

于 2013-10-22T02:34:19.513 回答