【问题标题】:pthread_join and pthread weird behaviourpthread_join 和 pthread 奇怪的行为
【发布时间】:2020-08-04 12:17:31
【问题描述】:

我有 2 个进程,每个进程通过下面的代码创建多个线程(本例中为 2 个)。当我将 pthread_join 放在 create 正下方时,它可以工作,但它总是按顺序调用线程。我想在不同的循环中进行连接,如下所示。问题是当我出于某种原因这样做时,它会创建双倍的同一线程而不是 2 个不同的线程。

因此,当线程运行时,它会打印出类似 “线程 2.2 开始 线程 2.2 开始 线程 1.2 开始 线程 1.2 开始” 其中第一个数字是进程号,第二个是线程号。它们应该是“1.2 1.1 2.1 2.2”。有人可以帮忙吗?

for(int i = 0; i<num_of_t;i++){
        struct threadst args;
        args.globalcp = globalcp;
        args.lock = lock;
        args.num1 = num1+i*((num2-num1+1)/num_of_t);
        args.num2 = args.num1+((num2-num1+1)/num_of_t)-1;
        args.threadid =i;
        args.pid = myOrder;
        pthread_create(&threads[i], &attr, findPrimes, (void *)&args);
        pthread_join(threads[i], &status);
    }

    //for(int i = 0; i<num_of_t;i++){
        //pthread_join(threads[i], &status);
    //}

【问题讨论】:

  • 您将相同struct threadst args 的地址传递给所有新线程并且没有任何同步。这是未定义的行为。
  • num1 和 num2 未定义。
  • 好吧,我调查了一下,我认为 G.M 是对的,我更正了这一点,现在正在创建不同的线程。但是每个都被调用两次。我确信我在某个地方犯了另一个错误。无论如何谢谢
  • 请以tour 开头并阅读How to Ask。此外,您的问题要求您提取 minimal reproducible example 并将其作为问题的一部分提供。

标签: c++ c multithreading unix pthreads


【解决方案1】:

首先,您在每个线程创建时传递相同的对象 (&amp;args),因此它在所有线程之间共享。所以根据需要给每个人自己的。

其次,不要在线程创建后立即调用pthread_join,否则会重新引入顺序性(join 是等待线程结束的阻塞操作)。通常你需要启动你的线程,然后在稍后的某个时间点调用你需要等待的线程上的 join。

// create an array of args to be passed each for a given thread
struct threadst *args = malloc(sizeof(struct threadst)*num_of_t;
// need a test for malloc...

for(int i = 0; i<num_of_t;i++){
    struct threadst *arg = args+i;
    arg->globalcp = globalcp;
    arg->lock     = lock;
    arg->num1     = num1+i*((num2-num1+1)/num_of_t);
    arg->num2     = arg->num1+((num2-num1+1)/num_of_t)-1;
    arg->threadid = i;
    arg->pid      = myOrder;
    pthread_create(&threads[i], &attr, findPrimes, (void *)arg);
}

// do something else in the meantime

for (int i = 0; i<num_of_t;i++) {
    pthread_join(threads[i], &status);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多