【问题标题】:Confusion with posix threads in cpp与cpp中的posix线程混淆
【发布时间】: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


【解决方案1】:

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

for (auto th : threads) {

那应该是:

for (auto& th : threads) {

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

另请注意,thread1thread2 在您的程序中无用,应将其删除。启用编译器警告会告诉您这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多