【发布时间】:2023-01-22 22:32:54
【问题描述】:
我真的很困惑这个特定的代码。 AFAIK,这个程序不应该有竞争条件,但它有。真正令人困惑的是删除循环并仅复制代码就可以正常工作。
注意:我看到一个关于循环中线程的问题,但它并没有真正捕捉到我试图强加的内容。
这里是
#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;
}
构建如下
FILE=mutex
all:
g++ $(FILE).cpp -lpthread -o bin && ./bin
我期望计数器变量每个线程递增一次,但有时没有打印其他时间计数器变量在我读过的两次执行中保持 1 是由于低级调度操作。
【问题讨论】:
-
你在什么操作系统上运行?您使用的是什么特定的编译器版本?
标签: c++ multithreading pthreads mutex