Я пытаюсь создать четыре потока, которые печатают какое-то сообщение.
У меня возникла проблема с синхронизацией.Планирование нескольких потоков с использованием Mutex и переменной условий
Вот что мой main()
выглядит
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int count = 4;
int main (void)
{
pthread_t thread1, thread2, thread3, thread4;
pthread_create (&thread4, NULL, function4, NULL);
pthread_create (&thread3, NULL, function3, NULL);
pthread_create (&thread2, NULL, function2, NULL);
pthread_create (&thread1, NULL, function1, NULL);
pthread_join (thread1, NULL);
pthread_join (thread2, NULL);
pthread_join (thread3, NULL);
pthread_join (thread4, NULL);
return 0;
}
function1()
отпечатков Function 1
, function2()
печатает Function 2
и так далее.
Желаемая выход должен быть следующим:
Function 1
Function 2
Function 3
Function 4
Фактический выход:
Function 1
/* Infinitely runs (Deadlock maybe) */
Актуальна:
Можно ли использовать один переменной условия для синхронизации двух или более потоков? Если да, то как?
Если нет, то как решить эту проблему?
Вот это определение function(n)
void *function1()
{
while (1)
{
if (count == 4)
{
pthread_mutex_lock (&mutex);
printf("Function 1\n");
count --;
pthread_mutex_unlock (&mutex);
pthread_cond_signal (&cond);
return NULL;
}
else
pthread_cond_wait(&cond, &mutex);
}
return NULL;
}
void *function2()
{
while (1)
{
if (count == 3)
{
pthread_mutex_lock (&mutex);
printf("Function 2\n");
count--;
pthread_mutex_unlock (&mutex);
pthread_cond_signal (&cond);
return NULL;
}
else
pthread_cond_wait(&cond, &mutex);
}
return NULL;
}
void *function3()
{
while (1)
{
if(count == 2)
{
pthread_mutex_lock (&mutex);
printf("Function 3\n");
count--;
pthread_mutex_unlock (&mutex);
pthread_cond_signal (&cond);
return NULL;
}
else
pthread_cond_wait(&cond, &mutex);
}
return NULL;
}
void *function4()
{
while (1)
{
if(count == 1)
{
pthread_mutex_lock (&mutex);
printf("Function 4\n");
pthread_mutex_unlock (&mutex);
pthread_cond_signal (&cond);
return NULL;
}
else
pthread_cond_wait(&cond, &mutex);
}
return NULL;
}
Обратите внимание, что вы должны использовать 'pthread_cond_wait', удерживая блокировку мьютекса. – juhist