I have a school project that requires me to wrote a program printing this: <ONE><TWO><THREE><ONE><TWO><THREE><ONE><TWO><THREE>…..............
using 3 threads and mutex. I have tried to do it with some help of the class, but it just keeps printing only <ONE>
. Can you help me solve my problem and understand what have i wrong?
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *func(void *arg)
{
pthread_mutex_lock(&mutex);
while (1) {
printf ("<ONE>");
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *func2(void *arg)
{
pthread_mutex_lock(&mutex);
while (1) {
printf ("<TWO>");
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *func3(void *arg)
{
pthread_mutex_lock(&mutex);
while (1) {
printf ("<THREE>");
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
main()
{
pthread_t mythread1,mythread2,mythread3;
pthread_create( &mythread1, NULL, func, (void *) 1);
pthread_create( &mythread2, NULL, func2, (void *) 2);
pthread_create( &mythread3, NULL, func3, (void *) 3);
pthread_join ( mythread1, NULL);
pthread_join ( mythread2, NULL);
pthread_join ( mythread3, NULL);
exit(0);
}