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?
&i
as the thread argument will cause problems, sincei
may change before a thread prints it. Simplest fix is probably to passi
cast to pointer instead. (this is in addition to thejoin()
problem already noted in the answers you've received) – Dmitri