3
我一直在编写一个关于线程同步的测试程序,用于学校的大型项目。我编写的一个测试程序是测试“semaphore.h”库的一小段代码。代码如下:Unix信号量问题
#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;
}
的“暴击”变量的最终值应为十万元,但我只得到数字接近它,表示竞争条件。我将我的代码与其他样本进行了比较,看起来不错,但我仍然遇到同样的问题。有什么想法吗?
信号量对于pthread的初学者来说确实是一个坏主意。 'sem_'调用通常太低。他们可能会被中断。你必须检查所有pthread/sem函数的所有*返回值。如果有错误代码,请分析代码和“errno”并采取相应措施。如果可能的话,用互斥/条件更好地重新编程您的示例。这些是更简单的工具,它们是POSIX中的“默认”控制结构。 –
尽管Jens的建议是有效的,我同意,但我无法重现您的问题。首先检查这些sem_函数的所有返回值。 –
我检查了返回值,并且存在'-1'问题。这使我朝着正确的方向前进。我会使用除“semaphore.h”以外的东西,但它是项目所必需的。谢谢Jen。 – user2904876