Question

I have this code changed, but is not working to print 1 2 3 4 5 6 what is missing?? I have tried to put two mutexes one between each creation of the thread, and another one when they are printed, but i always get 3 4 5 6 1 2. Thanks in advance.

pthread_mutex_t mutex;
pthread_mutex_t mutexd;
void *th(void *arg){
int *tmp=(int*)arg;
    pthread_mutex_lock(&mutexd);
    printf("%d\t",tmp[0]);
    printf("%d\t",tmp[1]);
    pthread_mutex_unlock(&mutexd);

}

int main(){
    pthread_mutex_init(&mutex,NULL);
    pthread_mutex_init(&mutexd,NULL);

    pthread_t threads[3];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
    pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);
    int t[]={1,2,3,4,5,6};
    pthread_mutex_lock(&mutex);
    pthread_create(&threads[0],&attr,th,(void *)t);
    pthread_mutex_unlock(&mutex);
    pthread_mutex_lock(&mutex);
    pthread_create(&threads[1],&attr,th,(void *)(t+2));
     pthread_mutex_unlock(&mutex);
    pthread_mutex_lock(&mutex);

    pthread_create(&threads[2],&attr,th,(void *)(t+4));
      pthread_mutex_unlock(&mutex);

    int i;
    for(i=0;i<THREADS;i++){
            pthread_join(threads[i],NULL);
    }
    putchar('\n');
    return 0;


}
Was it helpful?

Solution

thread don't usually work in the same order that they written in your code . in order to achieve this move each join to be after the creation of the thread.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
pthread_mutex_t mutex;
pthread_mutex_t mutexd;
void *th(void *arg)
{
    int *tmp=(int*)arg;

    pthread_mutex_lock(&mutexd);
    printf("%d\t",tmp[0]);
    printf("%d\t",tmp[1]);

    pthread_mutex_unlock(&mutexd);

}

int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_mutex_init(&mutexd,NULL);

    pthread_t threads[3];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
    pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);


    int t[]= {1,2,3,4,5,6};

    pthread_mutex_lock(&mutex);

    pthread_create(&threads[0],&attr,th,(void *)t);
     pthread_join(threads[0],NULL);
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);
    pthread_create(&threads[1],&attr,th,(void *)(t+2));
     pthread_join(threads[1],NULL);
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);
    pthread_create(&threads[2],&attr,th,(void *)(t+4));
     pthread_join(threads[2],NULL);
    pthread_mutex_unlock(&mutex);

    putchar('\n');
    return 0;


}

this code should work fine

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top