#include
#include
#include #include #define PTHREAD_NUM 3void *print_a(void *);
void *print_b(void *);
void *print_c(void *);
typedef void *(*pthread_func_t)(void *);
struct abc_demo{
int flag;
pthread_mutex_t mutex;
pthread_cond_t cond;
char *retval[PTHREAD_NUM];
pthread_t tid_array[PTHREAD_NUM];
pthread_func_t pfunc_array[PTHREAD_NUM];
};
struct abc_demo abc = {
.pfunc_array = {print_a,print_b,print_c},
};
static int g_count = 0;
void *print_a(void *arg)
{
while(1){pthread_mutex_lock(&(abc.mutex));
while(abc.flag != 0){
pthread_cond_wait(&(abc.cond), &(abc.mutex));
}
printf("A-----%d-----\n", g_count++);
abc.flag = 1;
pthread_mutex_unlock(&(abc.mutex));
pthread_cond_broadcast(&(abc.cond));
sleep(1);
if(g_count == 5)
pthread_exit((void *) 1);
}
}void *print_b(void *arg)
{
while(1){
pthread_mutex_lock(&(abc.mutex));
while(abc.flag != 1){
pthread_cond_wait(&(abc.cond), &(abc.mutex));
}
printf("B\n");
abc.flag = 2;
pthread_mutex_unlock(&(abc.mutex));
pthread_cond_broadcast(&(abc.cond));
sleep(1);
if(g_count == 5)
pthread_exit((void *) 1);
}
}void *print_c(void *arg)
{
while(1){
pthread_mutex_lock(&(abc.mutex));
while(abc.flag != 2){
pthread_cond_wait(&(abc.cond),&(abc.mutex));
}
printf("C\n");
abc.flag = 0;
pthread_mutex_unlock(&(abc.mutex));
pthread_cond_broadcast(&(abc.cond));
sleep(1);
if(g_count == 5)
pthread_exit((void *) 1);
}
}int main(int argc, char const *argv[])
{
int i,ret;
abc.flag = 0;
pthread_mutex_init(&(abc.mutex), NULL);
pthread_cond_init(&(abc.cond),NULL);
for(i = 0;
i < PTHREAD_NUM;
i++)
{
ret = pthread_create(abc.tid_array+i, NULL, abc.pfunc_array[i], NULL);
if(ret < 0)
{
perror("pthread_create");
return -1;
}
}
for(i = 0;
i < PTHREAD_NUM;
i++)
{
ret = pthread_join(abc.tid_array[i],(void **)abc.retval+i);
if(ret < 0)
{
perror("pthread_join");
return -1;
}
}
pthread_mutex_destroy(&(abc.mutex));
pthread_cond_destroy(&(abc.cond));
return 0;
}
测试结果 【互斥锁与条件变量实现按照顺序打印ABC】
文章图片
推荐阅读
- android|IPC方式(ContentProvider、Socket、Binder连接池)--《Android开发艺术探索》阅读笔记——第二章part4
- 使用线程的互斥锁实现生产者消费者模型
- 使用互斥锁实现字符串的逆置
- 使用三个线程下的信号量实现顺序打印ABC