简体   繁体   中英

pthread_join and pthread weird behaviour

I have 2 processes each creating multiple threads(2 in this example) via below code. When I put pthread_join right below create it works but it always calls threads in order. 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.

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". 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. 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). Usually you need to launch your threads, and at some subsequent point later in time call join on threads you need to wait for.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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