pthread_cond_signal函数的例子
时间: 2023-11-04 19:16:59 浏览: 96
下面是一个使用pthread_cond_signal函数的例子:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 3
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int count = 0;
void *thread_func(void *arg) {
int *id = (int *) arg;
printf("Thread %d started\n", *id);
pthread_mutex_lock(&mutex);
while (count < 5) {
printf("Thread %d waiting\n", *id);
pthread_cond_wait(&cond, &mutex);
printf("Thread %d continuing\n", *id);
}
pthread_mutex_unlock(&mutex);
printf("Thread %d finished\n", *id);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
int ids[NUM_THREADS] = {0, 1, 2};
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, thread_func, &ids[i]);
}
pthread_mutex_lock(&mutex);
for (int i = 0; i < 5; i++) {
count++;
printf("Main thread signalling\n");
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
在该例子中,我们创建了三个线程并在主线程中使用pthread_cond_signal函数通知等待线程继续执行。线程等待条件变量cond,当主线程调用pthread_cond_signal函数时,其中一个线程将从等待中醒来并继续执行。注意,我们在使用条件变量时需要使用互斥锁mutex来保护共享数据。
阅读全文