#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define PTHREAD_NUM 10
static int global = 0;
static pthread_mutex_t m;
static pthread_cond_t v;
void *count_times(void *args)
{
int i = 1;
while(1)
{
sleep(1);
fprintf(stderr, "second: %d\n", i++);
}
return (void *)0; //等价于NULL
}
void *tfn(void *args)
{
pthread_mutex_lock(&m);
while(global != 100)
{
//进入该函数,做两件事情:1.解锁,2.阻塞
pthread_cond_wait(&v, &m); //在此形成阻塞队列
//收到pthread_cond_broadcast, 从该函数返回做一件事:加锁
}
//临界区(进程中访问临界资源的那段代码)
fprintf(stdout, "t%d:global = %d\n", (int)args, global);
pthread_mutex_unlock(&m);
return (void *)0;
}
int main(void)
{
int i;
pthread_t tidd;
pthread_t tid[PTHREAD_NUM];
pthread_mutex_init(&m, NULL);
pthread_cond_init(&v, NULL);
pthread_create(&tidd, NULL, count_times, NULL);
for(i=0; i<PTHREAD_NUM; i++)
{
if(pthread_create(&tid[i], NULL, (void *)tfn, (void *)i) != 0)
{
perror("pthread_create failed");
}
}
sleep(1);
pthread_mutex_lock(&m);
global = 100;
pthread_cond_broadcast(&v); //向所有等待条件的线程发送信号
sleep(3);
pthread_mutex_unlock(&m);
for(i=0; i < PTHREAD_NUM; i++)
{
pthread_join(tid[i], NULL);
}
return 0;
}