与cpp中的posix线程混淆



我对这段代码真的很困惑。据我所知,这个程序不应该有竞争条件,但它确实有。真正令人困惑的是删除循环,只是复制代码工作得很好。

注意:我看到一个关于循环中的线程的问题,但它并没有真正捕捉到我想要强加的东西。

在这里

#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: %dn", counter);
pthread_mutex_unlock(&mutex1);
return NULL;
}

构建如下

FILE=mutex
all:
g++ $(FILE).cpp -lpthread -o bin && ./bin

我期望计数器变量每个线程增加一次,但有时没有打印,其他时候计数器变量在两次执行中都保持1,这是由于低级调度操作。

您的错误在这里(两个地方,其中第一个是关键的):

for (auto th : threads) {

应该是:

for (auto& th : threads) {

它需要是一个引用,这样当你把th的地址传递给pthread_create()时,你实际上传递的是threads[0]的地址,而不仅仅是th的地址。

还要注意thread1thread2在您的程序中是无用的,应该删除。启用编译器警告会告诉你这一点。

最新更新