这是互斥锁的经典示例。我不知道为什么下面的代码不起作用,即。它不会每次都打印“ctr = 0”(但是,例如,ctr = 535)。两个线程,第一个添加第二个替代品
int ctr;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void * add (void * arg_wsk)
{
int i;
for (i = 0; i < 100000; i++) {
pthread_mutex_lock (&m);
ctr++;
pthread_mutex_unlock (&m);
}
return(NULL);
}
void * sub(void * arg_wsk)
{
int i;
for (i = 0; i < 100000; i++) {
pthread_mutex_lock (&m);
ctr--;
pthread_mutex_unlock (&m);
}
return(NULL);
}
int main()
{
pthread_t tid1, tid2;
int i;
void *res;
ctr = 0;
pthread_mutex_init(&m, NULL);
pthread_create(&tid1, NULL, add, NULL);
pthread_detach(tid1);
pthread_create(&tid2, NULL, sub, NULL);
pthread_detach(tid2);
pthread_join(tid1, &res);
pthread_join(tid2, &res);
pthread_mutex_destroy(&m);
printf("ctr = %d", ctr);
pthread_exit(NULL);
}
你能指点我正确的方向吗?
此外,stackoverflow告诉我提供一些更多的细节,我的问题主要是代码。但是我真的不知道在这里写什么,我只是希望当我有更多的声望时这条消息会消失。
未能检查任何pthread库返回值意味着您可能忽略了一个重要的错误。 – kmarsh