【发布时间】:2021-11-26 22:36:01
【问题描述】:
我正在尝试执行此操作,但无法正常工作。 我有一个名为 counter 的全局变量,它从 100 开始,我有两个线程。 如果 counter 为 != 0,则两个线程都在运行 while 循环中递减计数器。 但是,尽管确实将计数器减为 0 的线程将按预期停止运行。但是不递减计数器的线程在它应该停止时继续运行。
我该如何解决这个问题?
下面是我的代码:
int counter = 0;
pthread_mutex_t counter_mutex;
void *Thread1(void *vargs)
{
while (counter != 0) {
pthread_mutex_lock(&counter_mutex);
counter--;
pthread_mutex_unlock(&counter_mutex);
}
sleep(1);
printf("Completed Thread1\n");
return NULL;
}
void *Thread2(void *vargs)
{
while (counter != 0) {
pthread_mutex_lock(&counter_mutex);
counter--;
pthread_mutex_unlock(&counter_mutex);
}
sleep(1);
printf("Completed Thread2\n");
return NULL;
}
int main(void)
{
pthread_t tid[2];
// initialize the mutex
pthread_mutex_init(&counter_mutex, NULL);
// create worker threads
pthread_create(&tid[0], NULL, Thread1, NULL);
pthread_create(&tid[1], NULL, Thread2, NULL);
// wait for worker threads to terminate
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
// print final counter value
printf("Counter is %d\n", counter);
return 0;
}
输出:
Completed Thread1
Thread1 completes but the program runs indefinitely because Thread2 stays in the while loop and doesn't finish.
Or vice versa, where Thread2 completes and then runs indefinitely because Thread1 stays
in the while loop and doesn't finish.
我真的很困惑如何解决这个问题,因为两个线程应该在 counter == 0 时运行和停止。但是只有计数器递减到 0 的线程会停止,而另一个线程会无限期地运行。
非常感谢任何和所有的帮助!
非常感谢
【问题讨论】:
-
您有一些未定义的变量(
g_Counter和g_Mutex)。 -
也许可以尝试
while (counter > 0)而不是while (counter != 0)- 如果一个线程减少了太多,另一个线程将继续运行。 -
我修好了。它可能是计数器和互斥锁。我也试过做 counter > 0 。它仍然给出同样的问题。
标签: c multithreading pthreads