博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
inux多线程顺序控制的示例
阅读量:6886 次
发布时间:2019-06-27

本文共 1215 字,大约阅读时间需要 4 分钟。

hot3.png

#include <pthread.h>

#include <cstdio>

#include <unistd.h>

const int THREAD_NUMBER = 3;

//  同步与互斥

pthread_mutex_t mutex;

pthread_mutex_t thread_mutex[THREAD_NUMBER];

pthread_cond_t thread_cond[THREAD_NUMBER];

pthread_cond_t cond;

int     a[3] = {0}; //用于线程与主线程通信,表示 子线程已经起动

// 

void *thread_func(void *arg);

int main(int argc, char **argv)

{

    pthread_t tids[THREAD_NUMBER];

    for (int i = 0; i < THREAD_NUMBER; ++i)

    {

        pthread_mutex_init(&thread_mutex[i], NULL);

        pthread_cond_init(&thread_cond[i], NULL);

    }

    pthread_mutex_init(&mutex, NULL);

    pthread_cond_init(&cond, NULL);

    for (int i = 0; i < THREAD_NUMBER; ++i)

    {

        pthread_create(&tids[i], NULL, thread_func, (void *)i);

    }

    while(1)

    {

        int i = 0;

        for(; i<THREAD_NUMBER; i++)

        {

            if(a[i]==0)

            {

                break;

            }

        }

        if(i>2)

        {

            break;

        }

        sleep(1);

    }

    pthread_cond_signal(&thread_cond[0]);

    for (int i = 0; i < THREAD_NUMBER; ++i)

    {

        pthread_join(tids[i], NULL);

    }

    printf("\n");

    return 0;

}

void *thread_func(void *arg)

{

    int id = *(int*)(&arg);

    char ch = 'A' + id;

    int count = 10;

    a[id] = 1;

    while (count--)

    {

        pthread_cond_wait(&thread_cond[id], &thread_mutex[id]);

        printf("%c", ch);

        pthread_cond_signal(&thread_cond[(id+1)%3]);

    }

    return (void *)0;

}

               

转载于:https://my.oschina.net/qichang/blog/205734

你可能感兴趣的文章
acl_cpp 编程之 xml 流式解析与创建
查看>>
Web端开发发展历程简单概述
查看>>
无聊的函数和方法之间的区别讨论
查看>>
最值得收藏的30本MySQL精品电子书
查看>>
android的消息处理机制(图+源码分析)——Looper,Handler,Message
查看>>
人脸识别 以及SoundPool 学习笔记
查看>>
内核启动过程
查看>>
王峰:数据中心全面迈入云时代
查看>>
二维码扫描和生成
查看>>
hbase-0.98整合hadoop-2.6,附java操作代码
查看>>
同一台电脑运行两个tomcat
查看>>
开源 免费 java CMS - FreeCMS1.4-功能说明-栏目管理
查看>>
Maven 是怎样创建War 包?
查看>>
Android4.2蓝牙Enable完全分析
查看>>
手动部署QtSylixOS的方法
查看>>
p6spy监控sql语句
查看>>
排序算法总结(java实现)(一.冒泡排序)
查看>>
排序算法总结(java实现)(二.插入排序)
查看>>
CMD 乱码永久解决方案
查看>>
Java EE6核心特征:Bean Validation
查看>>