多线程跑调度_linux多线程的调度问题

#include

#include

#include

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位置改了也不行~ 如上改在解锁后面还是不行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值