/*类型cnd_t范例*/
/*
** 该例子创建了4个新线程,
** 其中3个线程用于修改number的值,第4个线程处于等待状态;
** 如果number的值大于等于LIMIT,第4个线程输出number的值。
*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#define LIMIT 100 //解锁因条件变量而阻塞的线程的条件。
#define THREADS 4 //线程数。
unsigned int number = 0; //如果number≥LIMIT,解锁因条件变量而阻塞的线程。
mtx_t mutex; //互斥。
cnd_t conditionVariable; //条件变量。
/*操作number的函数。*/
int funcProcess(void *arg)
{
do
{
mtx_lock(&mutex);
/*如果条件满足就解锁因条件变量而阻塞的线程。*/
if(number >= LIMIT)
{
cnd_signal(&conditionVariable);
mtx_unlock(&mutex);
thrd_exit(0);
}
number += *((unsigned int *)arg);
mtx_unlock(&mutex);
}while(number < LIMIT);
}
/*等待number值满足条件的函数。*/
int funcWait(void *arg)
{
mtx_lock(&mutex);
while(number < LIMIT)
{
cnd_wait(&conditionVariable, &mutex);
}
puts("Receive condition signal.");
printf("number = %u\n", number);
mtx_unlock(&mutex);
thrd_exit(0);
}
int main(void)
{
thrd_t threadId[THREADS]; //线程标识符。
unsigned int data[THREADS-1] = {3, 6, 9};
/*初始化条件变量。*/
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);
}
/*创建新线程。*/
for(int i=0; i<THREADS-1; ++i)
{
if(thrd_create((threadId+i), funcProcess, (data+i)) != thrd_success)
{
perror("thrd_create");
exit(EXIT_FAILURE);
}
}
if(thrd_create((threadId+THREADS-1), funcWait, NULL) != 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;
}
|