这是互斥锁的经典例子。我不知道为什么以下代码不起作用,即。它不会每次都打印“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);
}
最佳答案
我认为您滥用了 POSIX API。如果你分离线程,你不应该加入它们。删除分离,看看这是否改善了事情。我想您会看到 main() 现在会阻塞,直到线程完成。
另请注意,来自加入通话的链接
ESRCH No thread could be found corresponding to that specified by the
given thread ID.
如果你幸运的话,你会碰到这个的。如果你不走运,疯狂的事情就会发生。不要在同一线程上混合分离和加入调用。
关于c - 两个线程,首先添加第二个减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638317/