4
votes

I want to make parallel threads. Example: my output is like: thread1 thread3 thread4 thread2... In main:

pthread_t tid;
int n=4;
int i;
for(i=n;i>0;i--){
    if(pthread_create(&tid,NULL,thread_routine,&i)){
        perror("ERROR");
    }
    pthread_join(tid,NULL);
}

And my function(routine) is:

void *thread_routine(void* args){
    pthread_mutex_lock(&some);
    int *p=(int*) args;
    printf("thread%d ",*p);
    pthread_mutex_unlock(&some);
}

I always got result not parallel: thread1 thread2 thread3 thread4. I want this threads running in same time - parallel. Maybe problem is position pthread_join, but how can I fix that?

2
Passing &i as the thread argument will cause problems, since i may change before a thread prints it. Simplest fix is probably to pass i cast to pointer instead. (this is in addition to the join() problem already noted in the answers you've received)Dmitri
@Dmitri Yeah this is problem here.Nejc Galof

2 Answers

4
votes

You want to join the thread after you have kicked off all of the threads. What your code currently does is starts a thread, then joins, then starts the next thread. Which is essentially just making them run sequentially.

However, the output might not change, because that happens based solely on whichever thread gets to the lock first.

0
votes

Yes, the join is preventing any of the threads from running concurrently, because it is blocking the main thread from continuing creating other threads until the just-created thread terminates. Remove the join and they should run concurrently. (Though possibly still not parallel depending on your system.)

However, you might not see any difference in your output.