zoukankan      html  css  js  c++  java
  • 条件变量和互斥锁

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 #include<unistd.h>
     5 #include<pthread.h>
     6 #include<errno.h>
     7 #include<iostream>
     8 using namespace std;
     9 
    10 /*提示出租车到达的条件变量*/
    11 pthread_cond_t taxiCond = PTHREAD_COND_INITIALIZER;
    12 /*同步锁*/
    13 pthread_mutex_t taxiMutex = PTHREAD_MUTEX_INITIALIZER;
    14 
    15 int travelerCount = 0;
    16 
    17 void *traveler_arrive(void* name) {
    18     cout << "Travel:" << (char*)name << "need a taxi now!" << endl;
    19     pthread_mutex_lock(&taxiMutex);
    20     travelerCount++;
    21     pthread_cond_wait(&taxiCond,&taxiMutex);
    22     pthread_mutex_unlock(&taxiMutex);
    23     cout << "Traveler:" << (char*)name << "now got a taxi!" << endl;
    24     pthread_exit((void*)0);
    25 }
    26 void *taxi_arrive(void *name) {
    27     cout << "Taxi:" << (char*)name << "arrives." << endl;
    28     while (1) {
    29         pthread_mutex_lock(&taxiMutex);
    30         if (travelerCount > 0) {
    31             pthread_cond_signal(&taxiCond);
    32             pthread_mutex_unlock(&taxiMutex);
    33             break;
    34         }
    35         pthread_mutex_unlock(&taxiMutex);
    36     }
    37     pthread_exit((void*)0);
    38 }
    39 
    40 int main() {
    41     pthread_t tids[3];
    42     int iRet = pthread_create(&tids[0], NULL, taxi_arrive, (void*)(" Jack "));
    43     if (iRet) {
    44         printf("pthread_creat error: iRet = %d
    ", iRet);
    45         return iRet;
    46     }
    47     printf("Time passing by
    ");
    48     sleep(1);
    49     iRet = pthread_create(&tids[1], NULL, traveler_arrive, (void*)(" Susan "));
    50     if (iRet) {
    51         printf("pthread_creat error: iRet = %d
    ", iRet);
    52         return iRet;
    53     }
    54     printf("Time passing by
    ");
    55     iRet = pthread_create(&tids[2], NULL, taxi_arrive, (void*)(" Mike "));
    56     if (iRet) {
    57         printf("pthread_creat error: iRet = %d
    ", iRet);
    58         return iRet;
    59     }
    60     printf("Time passing by
    ");
    61     sleep(1);
    62     void *retval;
    63     for (int i = 0; i < 3; i++) {
    64         iRet = pthread_join(tids[i], &retval);
    65         if (iRet) {
    66             printf("Join error: iRet = %d
    ", iRet);
    67             return iRet;
    68         }
    69         printf("retval = %ld
    ", (long)retval);
    70     }
    71     return 0;
    72 }
  • 相关阅读:
    jenkins升级
    linux中查看端口号
    jenkins--master/slave模式---master是容器版---slave是非容器版
    jenkins编译时文件存放的位置
    pipline中替换tag变量
    postman(十):配置jenkins自动发送邮件(邮件包含测试报告)
    postman(九):postman接口测试脚本集成到jenkins
    postman(八):使用newman来执行postman脚本
    postman(七):运行集合,看所有请求执行结果
    postman(六):详解在Pre-request Script中如何执行请求
  • 原文地址:https://www.cnblogs.com/--lr/p/11247753.html
Copyright © 2011-2022 走看看