Threads do not work in parallel

I want to make parallel threads. Example: my output is similar: thread1 thread3 thread4 thread2 ... Basically:

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 (subroutine):

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

I always got the result not in parallel: thread1 thread2 thread3 thread4. I want these threads to run at the same time - in parallel. Maybe the problem is in the position of pthread_join, but how can I fix it?

+4
source share
2 answers

You want to join a thread after you release all the threads. What your code is currently doing is starting the stream, then combining, and then starting the next stream. Essentially, they just run them sequentially.

, , , .

+3

, , , . , . (, , .)

.

0

All Articles