• Linux 多线程编程—使用条件变量实现循环打印


    编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

    使用条件变量来实现:

     1 #include <pthread.h>
     2 #include <stdio.h>
     3 #include <unistd.h>
     4 static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
     5 
     6 static pthread_cond_t condA ;
     7 static pthread_cond_t condB ;
     8 static pthread_cond_t condC ;
     9 
    10 
    11 void* threadA(void *arg)
    12 {
    13 int a =10;
    14 while(a--)
    15 {
    16 //sleep(2);
    17 //printf("A begin.
    ");
    18 pthread_mutex_lock(&mtx);
    19 //printf("A wait.
    ");
    20 pthread_cond_wait(&condC,&mtx);
    21 printf("A.
    ");
    22 pthread_mutex_unlock(&mtx);
    23 pthread_cond_signal(&condA);
    24 }
    25 }
    26 
    27 void* threadB(void *arg)
    28 {
    29 int b=10;
    30 while(b--)
    31 {
    32 //sleep(2);
    33 //printf("B begin.
    ");
    34 pthread_mutex_lock(&mtx);
    35 //printf("B wait.
    ");
    36 pthread_cond_wait(&condA,&mtx);
    37 printf("B.
    ");
    38 pthread_mutex_unlock(&mtx);
    39 pthread_cond_signal(&condB);
    40 }
    41 }
    42 
    43 void* threadC(void *arg)
    44 
    45 {
    46 int c=10;
    47 while(c--)
    48 {
    49 //sleep(2);
    50 //printf("C begin.
    ");
    51 pthread_mutex_lock(&mtx);
    52 //printf("C wait.
    ");
    53 pthread_cond_wait(&condB,&mtx);
    54 printf("C.
    ");
    55 pthread_mutex_unlock(&mtx);
    56 pthread_cond_signal(&condC);
    57 }
    58 }
    59 int main (void *arg)
    60 {
    61 pthread_t tidA;
    62 pthread_t tidB;
    63 pthread_t tidC;
    64 pthread_cond_init(&condA,NULL);
    65 pthread_cond_init(&condB,NULL);
    66 pthread_cond_init(&condC,NULL);
    67 pthread_create(&tidA,NULL,&threadA,NULL);
    68 pthread_create(&tidB,NULL,&threadB,NULL);
    69 pthread_create(&tidC,NULL,&threadC,NULL);
    70 
    71 printf("main begin..
    ");
    72 sleep(4);
    73 pthread_cond_signal(&condC);
    74 
    75 pthread_join(tidA,NULL);
    76 pthread_join(tidB,NULL);
    77 pthread_join(tidC,NULL);
    78 
    79 return 0;
    80 }
  • 相关阅读:
    bloom filter
    Crowdsourcing(众包)
    瘦客户端
    如何书写高效的工作邮件:给你十条建议
    JSON
    MATLAB实现频数直方图——hist的使用
    Matlab中给figure添加图例(legend),标题(title)和颜色(color)
    数字信号处理中各种频率关系
    论文的写作要求、流程与写作技巧
    中继器、集线器(HUB)、网桥、交换机、路由器比较
  • 原文地址:https://www.cnblogs.com/harlanc/p/5155520.html
Copyright © 2020-2023  润新知