Write a program using 3 threads, one prints 10 'A's and the second prints 'B's and the third prints 10 'C's with synchrornization

Posted by user132967 on Programmers See other posts from Programmers or by user132967
Published on 2014-05-30T03:29:01Z Indexed on 2014/05/30 3:50 UTC
Read the original article Hit count: 196

Iam try to implement this questions using threads and mutex this is my code :

include

include

include

include

include

define Num_thread 3

pthread_mutex_t lett[Num_thread];

void Sleep_rand(double max) { struct timespec delai;

delai.tv_sec=max;
delai.tv_nsec=0;
nanosleep(&delai,NULL);

}

void *Print_Sequence();

int main() { int i; pthread_t tid[Num_thread];// this is threads identifier

for(i=0;i<Num_thread;i++)
pthread_mutex_init(&lett[i],0);


for(i=0;i<Num_thread;i++)

{ printf("i=%d\n",i); /* create the threads / pthread_create(&tid[i], / This variable will have the thread is after successful creation / NULL, / send the thread attributes / Print_Sequence, / the function the thread will run / &i/ send the parameter's address to the function */);

}

/* Wait till threads are complete and join before main continues */ for (i = 0; i

        pthread_join(tid[i], NULL);
}


return 0;

}

/* The thread will begin control in this function */ void Print_Sequence(void param) { int i,j=(int)param; printf("j=%d\n",(*j)); int max; pthread_mutex_lock(&lett[0]); pthread_mutex_lock(&lett[1]);

for (i = 1; i <= 10; i++)
{
    max=(int) (8*rand()/(RAND_MAX+1.0));
    Sleep_rand( max);


    printf("A");

}
pthread_mutex_unlock(&lett[0]);
pthread_mutex_lock(&lett[2]);


for (i = 1; i <= 10; i++)

{ max=(int) (2*rand()/(RAND_MAX+1.0)); Sleep_rand( max);

    printf("B");

}

for (i = 1; i <= 10; i++)
{
    max=(int) (15*rand()/(RAND_MAX+1.0));
    Sleep_rand( max);

    printf("C");

}


pthread_mutex_unlock(&lett[1]);
 pthread_mutex_unlock(&lett[2]);

pthread_exit(0);

}

and the o/p is like : AAAAAAAAAABBBBBBBBBBCCCCCCCCCCAAAAAAAAAABBBBBBBBBBCCCCCCCCCCAAAAAAAAAABBBBBBBBBBCCCCCCCCCC

COULD ANYONE PLEASE EXPLAIN WHAT IS THE WRONG WITH CODE ??

© Programmers or respective owner

Related posts about multithreading

Related posts about synchronization