zoukankan      html  css  js  c++  java
  • 多线程输出奇偶数

    #include <pthread.h>
    #include <iostream>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdio.h>
    using namespace std;
    pthread_cond_t qready = PTHREAD_COND_INITIALIZER; 
    pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
    bool flag = false;
    int i = 0;
    void* PrintA(void *arg){
        while(1){
            pthread_mutex_lock(&qlock);
            pthread_cond_wait(&qready,&qlock);
            cout << "A = " << i << endl;
            i ++;
            pthread_mutex_unlock(&qlock);
            flag = false;
            if(i >= 100){
                break;
            }
        }
    }
    void* PrintB(void *arg){
        while(1){
            if(i >= 100)    break;
            if(flag == true)    continue;
            pthread_mutex_lock(&qlock);
            cout << "B = " << i << endl;
            i ++;
            pthread_mutex_unlock(&qlock);
            if(flag == false){
            flag = true;
            pthread_cond_signal(&qready);
            }
        }
    }
    int main(){
        pthread_t tid1, tid2;
        int iRet = pthread_create(&tid1, NULL, PrintA, NULL);
        iRet = pthread_create(&tid2, NULL, PrintB, NULL);
        void * retval;
        iRet = pthread_join(tid1, &retval);
        iRet = pthread_join(tid2, &retval);
        return 0;
    }
    
  • 相关阅读:
    easyui好例子,值得借鉴
    DDL 和DML 区别
    兼容IE的文字提示
    搭代理
    美国服务器
    跟随滚动条滚动
    JS Array对象
    JS 内置对象 String对象
    JS 对象
    JS 二维数组
  • 原文地址:https://www.cnblogs.com/qq136155330/p/12735314.html
Copyright © 2011-2022 走看看