【发布时间】:2017-04-02 19:08:21
【问题描述】:
考虑以下程序:
// 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。
-
是的,使用
pthread_cond_wait使用互斥锁。当每个条件都发出信号时,您应该阅读n并检查是否应该继续。 -
@JensMunk 在本案中如何使用?
-
看这里。 stackoverflow.com/questions/16522858/… 它解释了如何使用
pthread_cond_wait- 在增加循环计数时保持互斥锁n。
标签: c multithreading synchronization pthreads semaphore