Threads not running parallel

4.5k Views Asked by At

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

There are 2 best solutions below

3
On BEST ANSWER

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
On

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.