首页 > 解决方案 > 为什么在 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;
}

标签: clinuxpthreads

解决方案


睡眠参数是无符号整数秒。0.5 生成警告并假定为 0

“男人 3 睡觉”:

无符号整数睡眠(无符号整数秒);


推荐阅读