4

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?

Constantinius
  • 34,183
  • 8
  • 77
  • 85
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70
  • 1
    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 Dec 16 '14 at 16:56
  • @Dmitri Yeah this is problem here. – Nejc Galof Dec 17 '14 at 10:36

2 Answers2

4

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.

dhalik
  • 455
  • 3
  • 11
  • Soo here is no option to fix that to work parallel? – Nejc Galof Dec 16 '14 at 16:11
  • 1
    The fix would be to have a second loop after the first one with the join statement. But since you don't have any code after, you can simply let the threads finish on their own, and completely remove the join statement. – dhalik Dec 16 '14 at 16:28
  • If I have in new for loop for with join statement, result is not ok. Is like that: thread3 thread3 thread3 thread1 or something like that. – Nejc Galof Dec 16 '14 at 16:35
0

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.

Omaha
  • 2,262
  • 15
  • 18