开发者社区> 问答> 正文

linux多线程的调度问题

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t Poll_Work;       //互斥
pthread_cond_t Poll_Full;       //条件

void* thread0(void *param)
{
    
    while(*(int*)param < 100 && *(int*)param >= 0){
        pthread_mutex_lock(&Poll_Work);
        (*(int*)param) += 5;
        printf("Thread0: %d\n", *(int*)param);
        pthread_mutex_unlock(&Poll_Work);
                sleep(2);
    }
    pthread_cond_signal(&Poll_Full);
    return NULL;
}

void* thread1(void *param)
{
    while(*(int*)param < 100 ){
        pthread_mutex_lock(&Poll_Work);
        (*(int*)param) -= 5;
        printf("Thread1: %d\n", *(int*)param);
        pthread_mutex_unlock(&Poll_Work);
                sleep(2);
    }
    pthread_cond_signal(&Poll_Full);
    return NULL;
}

void* thread2(void *param)
{
    pthread_mutex_lock(&Poll_Work); 
    while(*(int*)param < 100) 
        pthread_cond_wait(&Poll_Full, &Poll_Work); 
    printf("Thread2: Poll Is Full!!\n");  
    pthread_mutex_unlock(&Poll_Work); 
    return NULL;
}

int main()
{
    int sum = 0;   //水深  满为100米 初始化 池里没有水
    int i;

    pthread_mutex_init(&Poll_Work, NULL);
    pthread_cond_init(&Poll_Full, NULL);
    pthread_t ths[3];
    pthread_create(&ths[0], NULL,  thread0, (void*)&sum);
    pthread_create(&ths[1], NULL,  thread1, (void*)&sum);
    pthread_create(&ths[2], NULL,  thread2, (void*)&sum);
    for(i = 0; i < 3; ++ i){
        pthread_join(ths[i], NULL);
    }
    printf("Play End!\n");
}

程序大概意思 一个可以装100水的pool 两个线程 一个不断加5 一个不断减3 第三个线程用于输出 当满的时候 输出Full 可是运行程序后 发现总是只有一个线程在运行 另一个完全没反应。 加了sleep也不见另一个线程被调度执行。

为什么呢?

sleep位置改了也不行~ 如上改在解锁后面还是不行。

展开
收起
a123456678 2016-06-16 14:13:08 1845 0
1 条回答
写回答
取消 提交回答
  • 因为你的sleep放错了地方,应该是放在 pthread_mutex_unlock 后面。

    另外,不建议使用sleep,建议使用pthread_yield来放弃cpu。

    然后你就会发现你的代码逻辑有些问题,比如说sum < 0了,thread1还在继续运行。

    2019-07-17 19:40:48
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Alibaba Cloud Linux 3 发布 立即下载
ECS系统指南之Linux系统诊断 立即下载
ECS运维指南 之 Linux系统诊断 立即下载