多线程--pthread_create, pthread_join

先看例子代码:

void CStudent::menuCallback(CCObject * pSender) {
    CStudent *temp = new CStudent("new student", 33);
    pthread_mutex_init(&mutex, NULL);//create a mutex
    pthread_create(&pidRun, NULL, run, temp); //create a thread
    void *run_thread_status = NULL;
    pthread_join(pidRun, &run_thread_status); // wait the thread dead,then execute the other threads
    pthread_create(&pidGo, NULL, go, 0);

    void *thrid_thread_status = NULL;
    pthread_join(pidGo, &thrid_thread_status);
    pthread_create(&pidThrid, NULL, thrid,NULL);
}

void CStudent::closeCallback(CCObject * pSender) {

}

void *run(void *r) {
    CStudent *pStudent = (CStudent *)r;
    do
    {
        CC_BREAK_IF(pStudent == 0);
        CCLog("Name: %s, age: %d\n", pStudent->getName(), pStudent->getAge());
        while(true) {
            pthread_mutex_lock(&mutex);
            if(ticket > 20) {
                CCLog("Thread Run Sell ticket: %d\n", ticket);
                --ticket;
                pthread_mutex_unlock(&mutex);
            } else {
                pthread_mutex_unlock(&mutex);
                break;
            }
            Sleep(1);
        }
    } while(false);
    return NULL;
}

void *go(void *g) {
    while(true) {
        pthread_mutex_lock(&mutex);
        if(ticket > 10 && ticket <= 20) {
            CCLog("Go Thread Sell ticket: %d\n", ticket);
            --ticket;
            pthread_mutex_unlock(&mutex);// the the mutex unsingled
        } else {
           pthread_mutex_unlock(&mutex);
           break;
        }
    
    }
    Sleep(1);
    return NULL;
}

void *thrid(void *t) {
    while(true) {
        pthread_mutex_lock(&mutex);
        if(ticket > 0 && ticket <= 10) {
            CCLog("Thrid thread Sell ticket: %d\n", ticket);
            --ticket;
            pthread_mutex_unlock(&mutex);
        } else {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return NULL;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值