Рассмотрим следующую программу:C pthread: как активировать один поток при выполнении условия?
// Compilation:
// gcc -Wall -Wextra -pedantic -Wno-unused-parameter -O3 test.c -o test -pthread
// Include
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
// Common variables
sem_t sem; // Semaphore
static const int nthr = 4; // Number of threads
static int n = 0; // Global counter
// Wait for a given number of seconds
void wait(unsigned int seconds)
{
unsigned int limit = time(NULL) + seconds;
while (time(NULL) < limit);
}
// Function f0
void* f0(void* arg)
{
while (n < 2); // Here
// Doing stuff that does no require any access to shared variable
printf("...doing stuff in f0...\n");
pthread_exit(NULL);
}
// Function fn
void* fn(void* arg)
{
sem_wait(&sem);
wait(1);
printf("entering fn: n = %d\n", n);
n++;
printf("leaving fn: n = %d\n", n);
wait(1);
sem_post(&sem);
pthread_exit(NULL);
}
// Main
int main(int argc, char* argv[])
{
pthread_t thr[nthr];
sem_init(&sem, 0, 1);
pthread_create(&thr[0], NULL, f0, NULL);
for (int i = 1; i < nthr; ++i) pthread_create(&(thr[i]), NULL, fn, NULL);
for (int i = 0; i < nthr; ++i) pthread_join(thr[i], NULL);
return 0;
}
Программа выполняет следующие действия: thread0
выполняет f0
в то время как другие потоки выполняются fn
. Я хочу, чтобы f0
дождался, пока два потока увеличили n
, прежде чем что-то делать.
Настоящая строка с пометкой Here
должна сделать это, но это не сработает. Как это сделать правильно (используя семафоры вместо мьютексов, когда это возможно)?
Вы можете использовать pthread_cond_t. – sturcotte06
Да, используйте 'pthread_cond_wait', используя мьютекс. Когда каждое условие сигнализируется, вы должны прочитать 'n' и проверить, следует ли продолжить. –
@JensMunk Как использовать его в данном случае? – Vincent