简体   繁体   English

pthread_join 和 pthread 奇怪的行为

[英]pthread_join and pthread weird behaviour

I have 2 processes each creating multiple threads(2 in this example) via below code.我有 2 个进程,每个进程通过下面的代码创建多个线程(在本例中为 2 个)。 When I put pthread_join right below create it works but it always calls threads in order.当我将 pthread_join 放在 create 正下方时,它可以工作,但它总是按顺序调用线程。 I want to do the joins in a different loop as below.我想在不同的循环中进行连接,如下所示。 Problem is when I do that for some reason it creates doubles of same thread instead of 2 different threads.问题是当我出于某种原因这样做时,它会创建双倍的相同线程而不是 2 个不同的线程。

So when thread runs it prints something like "Thread 2.2 started Thread 2.2 started Thread 1.2 started Thread 1.2 started" Where first number is process no and second one is thread no.They should be"1.2 1.1 2.1 2.2".因此,当线程运行时,它会打印类似“线程 2.2 已启动,线程 2.2 已启动,线程 1.2 已启动,线程 1.2 已启动”,其中第一个数字是进程号,第二个是线程号。它们应该是“1.2 1.1 2.1 2.2”。 Can someone help please?有人可以帮忙吗?

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);
    //}

First, you are passing the same object at each thread creation ( &args ), it is thus shared among all threads.首先,您在每个线程创建( &args )时传递相同的 object,因此它在所有线程之间共享。 So give each it's own as you needed.因此,根据需要给每个它自己的。

Second, don't call pthread_join just after thread creation or you will reintroduce sequentiality (join is a blocking operation waiting for the end of the thread).其次,不要在线程创建后立即调用pthread_join ,否则会重新引入顺序性(join 是等待线程结束的阻塞操作)。 Usually you need to launch your threads, and at some subsequent point later in time call join on threads you need to wait for.通常你需要启动你的线程,然后在稍后的某个时间点调用你需要等待的线程上的 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM