[英]Confusion with posix threads in cpp
I'm really confused with this particular code.我真的很困惑这个特定的代码。 AFAIK, this program should not have a race condition but it does.
AFAIK,这个程序不应该有竞争条件,但它有。 What is really confusing is removing the loops and just duplicating the code works fine.
真正令人困惑的是删除循环并仅复制代码就可以正常工作。
NOTE: I saw a question about threads in a loop but it does not really capture what i'm trying to impose.注意:我在循环中看到了一个关于线程的问题,但它并没有真正捕捉到我试图强加的内容。
Here it is这里是
#include <cstdio>
#include <cstdlib>
#include <pthread.h>
void *functionC(void*);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
int main() {
pthread_t thread1, thread2;
pthread_t threads[] = { thread1, thread2 };
for (auto th : threads) {
if (pthread_create(&th, NULL, &functionC, NULL) != 0)
{
printf("Thread Creation Failed");
}
}
for (auto th : threads) {
pthread_join(th, NULL);
}
exit(0);
}
void *functionC(void *) {
pthread_mutex_lock(&mutex1);
counter++;
printf("Counter Value: %d\n", counter);
pthread_mutex_unlock(&mutex1);
return NULL;
}
Built as follows构建如下
FILE=mutex
all:
g++ $(FILE).cpp -lpthread -o bin && ./bin
I was expecting the counter variable to increment once per thread but sometimes nothing prints other times the counter variable remains 1 for both executions which i have read is due to low level scheduling operations.我期望计数器变量每个线程递增一次,但有时没有打印其他时间计数器变量在我读过的两次执行中保持 1 是由于低级调度操作。
Your bug is here (two places, the first of which is critical):您的错误在这里(两个地方,第一个很关键):
for (auto th : threads) {
That should be:那应该是:
for (auto& th : threads) {
It needs to be a reference so that when you take the address of th
and pass it to pthread_create()
, you are actually passing the address of threads[0]
and not merely the address of th
.它需要是一个引用,这样当您获取
th
的地址并将其传递给pthread_create()
时,您实际上传递的是threads[0]
的地址而不仅仅是th
的地址。
Also note that thread1
and thread2
are useless in your program, and should be removed.另请注意,
thread1
和thread2
在您的程序中无用,应将其删除。 Enabling compiler warnings would tell you this.启用编译器警告会告诉您这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.