【练习】条件变量:创建三个线程 id号为ABC,三个线程循环打印自己的ID号,运行顺序为 ABCABC

题目:

  • 创建三个线程 id号为ABC,三个线程循环打印自己的ID号,运行顺序为 ABCABC......
  • 要求使用条件变量
#include 
#include 
#include 

//创建互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//条件变量创建
pthread_cond_t cond1 =PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 =PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 =PTHREAD_COND_INITIALIZER;
//限制访问机制
int flag=1;

void* callback1(void* arg)
{
    while(1)
    {
        /*************临界区**************/
        //上锁
        pthread_mutex_lock(&mutex);
        if(flag != 1)
        {
            //休眠 解锁
            pthread_cond_wait(&cond1,&mutex);
        }
        printf("A");
        flag=2;
        //唤醒
        pthread_cond_signal(&cond2);
        //解锁
        pthread_mutex_unlock(&mutex);
        /*************临界区**************/
    }
    pthread_exit(NULL);
}
void* callback2(void* arg)
{
    while(1)
    {
        /*************临界区**************/
        //上锁
        pthread_mutex_lock(&mutex);
        if(flag != 2)
        {
            //休眠 解锁
            pthread_cond_wait(&cond2,&mutex);
        }
        printf("B");
        flag=3;
        //唤醒
        pthread_cond_signal(&cond3);
        //解锁
        pthread_mutex_unlock(&mutex);
        /*************临界区**************/
    }
    pthread_exit(NULL);

}
void* callback3(void* arg)
{
    while(1)
    {
        /*************临界区**************/
        //上锁
        pthread_mutex_lock(&mutex);
        if(flag != 3)
        {
            //休眠 解锁
            pthread_cond_wait(&cond3,&mutex);
        }
        printf("C\n");
        flag=1;
        //唤醒
        pthread_cond_signal(&cond1);
        //解锁
        pthread_mutex_unlock(&mutex);
        /*************临界区**************/
    }
    pthread_exit(NULL);

}

int main(int argc, const char *argv[])
{
    //练习1.创建三个线程id号为ABC,要求三个线程循环打印自己的ID号, 运行顺序为ABCAB.....
    pthread_t A,B,C;
    if(pthread_create(&A,NULL,callback1,NULL)!=0)
    {
        fprintf(stderr,"pthread_create faild __%d__\n",__LINE__);
        return -1;
    }
    if(pthread_create(&B,NULL,callback2,NULL)!=0)
    {
        fprintf(stderr,"pthread_create faild __%d__\n",__LINE__);
        return -1;
    }
    if(pthread_create(&C,NULL,callback3,NULL)!=0)
    {
        fprintf(stderr,"pthread_create faild __%d__\n",__LINE__);                             
        return -1;
    }

    pthread_join(A,NULL);
    pthread_join(B,NULL);
    pthread_join(C,NULL);

    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
    //销毁条件变量
    pthread_cond_destroy(&cond1);
    pthread_cond_destroy(&cond2);
    pthread_cond_destroy(&cond3);
    return 0;
}
                                                                                              

运行结果:死循环输出ABC\n

ubuntu@ubuntu:04_pthread$ gcc t3.3pthread.c -pthread
ubuntu@ubuntu:04_pthread$ ./a.out 
ABC
ABC
ABC
ABC
ABC

你可能感兴趣的:(IO进程线程,#,线程,#,练习,linux,c#,c语言)