c - 为什么在 Linux 上的多线程中 sleep 不像 usleep 那样工作?
问题描述
在下面的程序中,如果我用sleep(0.5)替换usleep,那么它就不会像usleep一样睡眠,这背后的原因是什么?我试图搜索但没有找到答案。这发生在我的 Ubuntu 16.04 和 CentOS 8 中。提前致谢。
#include<unistd.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
void* mmmm(void* args){
int i=0;
while(i<1000){
printf("A:%d\n",i);
i++;
usleep(500000);
// sleep(0.5);
}
return NULL;
}
void* nnnn(void* args){
int j=1000;
while(j>0){
printf("B:%d\n",j);
j--;
usleep(500000);
// sleep(0.5);
}
return NULL;
}
int main(){
pthread_t a,b;
int errora = pthread_create(&a,NULL,mmmm,NULL);
int errorb = pthread_create(&b,NULL,nnnn,NULL);
printf("error A:%d,error B:%d\n",errora,errorb);
int status_a,status_b;
pthread_join(b,(void*)&status_b);
pthread_join(a,(void*)&status_a);
return 0;
}
解决方案
睡眠参数是无符号整数秒。0.5 生成警告并假定为 0
“男人 3 睡觉”:
无符号整数睡眠(无符号整数秒);
推荐阅读
- mysql - MySQL上出现此错误1241的原因可能是什么
- javascript - 这里地图自动缩放以适合所有标记
- javascript - 嵌套 App.post 和 App.get,好做法还是坏主意?
- pine-script - tradingview:Pine 无法确定系列的参考长度。尝试使用 max_bars_back
- c++ - std::set 用于双精度值的自定义比较函数。插入()不起作用
- mongodb - 无法将数据从我的独立实例导入 MongoDB atlas 集群
- powershell - Powershell:在一个属性上获取唯一性,同时对两个属性进行排序
- amazon-web-services - AWS EC2 上的 Gitlab Runner 自动缩放 - 无法生成实例
- sql - 如何在 GROUP BY 语句中排除唯一属性
- istio - Istio URI 与 Rewrite 匹配