考虑下面的程序: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
而其他线程执行fn
执行f0
。我想f0
等到两个线程在做某事之前增加n
。
当前行标记为Here
应该这样做,但它不起作用。如何正确使用(尽可能使用信号量而不是互斥量)?
您可以使用pthread_cond_t。 – sturcotte06
是的,使用'pthread_cond_wait'使用互斥锁。当每个条件发出信号时,您应该阅读'n'并检查是否应该继续。 –
@JensMunk如何在目前的情况下使用它? – Vincent