/*函数cnd_broadcast范例*/
/*
** 该例子创建了4个新线程,
** 其中1个线程用于数据处理,另外3个线程处于等待状态;
** 如果state的值为true,将唤醒所有等待线程。
*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#define THREADS 4 //线程数。
mtx_t mutex; //互斥。
cnd_t conditionVariable; //条件变量。
bool state = false;
/*数据处理函数。*/
int funcProcess(void *arg)
{
mtx_lock(&mutex);
/*数据处理后,将state的值设置为true。*/
state = true;
/*如果条件满足就解锁因条件变量而阻塞的线程。*/
if(state == true)
{
cnd_broadcast(&conditionVariable);
}
mtx_unlock(&mutex);
thrd_exit(0);
}
/*等待state值满足条件的函数。*/
int funcWait(void *arg)
{
mtx_lock(&mutex);
while(state == false)
{
cnd_wait(&conditionVariable, &mutex);
}
printf("Thread %d received condition signal.\n", *((int *)arg));
mtx_unlock(&mutex);
thrd_exit(0);
}
int main(void)
{
thrd_t threadId[THREADS]; //线程标识符。
int data[THREADS-1];
/*初始化条件变量。*/
if(cnd_init(&conditionVariable) != thrd_success)
{
perror("cnd_init");
exit(EXIT_FAILURE);
}
/*初始化互斥。*/
if(mtx_init(&mutex, mtx_plain) != thrd_success)
{
perror("mtx_init");
exit(EXIT_FAILURE);
}
/*创建新线程。*/
if(thrd_create(threadId, funcProcess, NULL) != thrd_success)
{
perror("thrd_create");
exit(EXIT_FAILURE);
}
for(int i=0; i<THREADS - 1; ++i)
{
data[i] = i + 1;
if(thrd_create((threadId+i+1), funcWait, (data+i)) != thrd_success)
{
perror("thrd_create");
exit(EXIT_FAILURE);
}
}
/*连接线程。*/
for(int i=0; i<THREADS; ++i)
{
thrd_join(threadId[i], NULL);
}
/*销毁条件变量和互斥。*/
cnd_destroy(&conditionVariable);
mtx_destroy(&mutex);
return 0;
}
|