c - 为什么我的所有线程都在使用 sleep() 休眠?

标签 c linux multithreading sleep

我在网上看到了以下一段关于 Linux 中线程的代码。但是当我运行它时,所有线程似乎都在 sleep ,而不仅仅是主线程。为什么?另外,没有sleep(5),语句-“线程创建成功”运行了3次而不是2次?有人可以解释这种行为吗?谢谢 编译使用: gcc -pthread 检查.c

和我的 o/p: 第一线程处理n 线程创建成功 第二线程处理n 线程创建成功

前两行打印有 5 秒的延迟,接下来的 2 行在 5 秒后打印。为什么子线程而不是主线程正在休眠?

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];

void* doSomeThing()

{
    unsigned long i = 0;
    pthread_t id = pthread_self();

    if (pthread_equal(id,tid[0]))
    {
        printf("\n First thread processingn");
    }
    else
    {
        printf("\n Second thread processingn");
    }
    return NULL;
}
int main(void)
{
    int i = 0;
    int err;
    while (i < 2)
    {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        sleep(5);
        if (err != 0)
            printf("\ncan't create thread [%s]", strerror(err))
            else

                printf("\n Thread created successfullyn");
        i++;
        // sleep(5);
    }
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);

    return 0;
}

最佳答案

为什么您认为所有线程都在休眠?阅读一些 pthreads tutorial & pthreads(7)

看起来您的线程很快就终止了。您应该使用 pthread_join(3) 加入它们(例如,在 sleep 之前,或 main 中的某处)

 for (int i=0; i<2; i++) {
    void* retval = NULL;
    pthread_join(tid[i], &retval);
    // in your case, since doSomething gives NULL :
    assert (retval == NULL); 
 }

或者您应该创建分离线程,请参阅 pthread_create(3) & 中的示例 pthread_attr_init(3) & pthread_attr_setdetachstate(3)等等……

你应该已经编码了(因为你希望 doSomeThing 得到一个 NULL 参数):

void* doSomeThing(void* arg) {
   assert (arg == NULL);

顺便说一句,请使用 gcc -Wall -Wextra -g 进行编译并学习如何使用 gdb 调试器。

您可能应该调用fflush(3) 在适当的地方(因为 stdio(3) 通常是 buffered ),例如在 doSomeThing

结束时调用 fflush(NULL);

了解 undefined behavior并努力避免它。

在您期望输出的线程中执行fflush(NULL); 很重要(至少在结束它们之前)。您的问题与 sleep 无关,但与缓冲有关。出于非常有效的性能原因,printf 经常被缓冲。并且您还应该养成使用 \n 结束 printf 格式控制字符串的习惯(因为这通常会刷新缓冲区)。将 \n 仅放在 printf 格式字符串的开头是一个坏习惯(应该放在末尾)。


顺便说一句,通过更正 void* doSomething(void*arg) 行(因为 void arg 在你的问题的原始版本中给出,代码甚至没有编译!)我在编译时观察到以下输出:

 % gcc -Wall -g x.c -pthread -o xx
   x.c: In function 'doSomeThing':
   x.c:11:19: warning: unused variable 'i' [-Wunused-variable]
        unsigned long i = 0;
                      ^

然后执行:

   % ./xx

   Thread created successfully

   First thread processing

   Thread created successfully

   Second thread processing

所以问题中给出的代码在我的电脑上并不像问题中解释的那样运行。因此Harsh S. Kulshrestha应该通过提供准确 源代码、完整的编译命令和准确 输出来编辑他的问题。 FWIW,我的系统是 x86-64 上的 Linux/Debian/Sid,gcc 是版本 4.9.2,libc 是 Debian GLIBC 2.19-15

关于c - 为什么我的所有线程都在使用 sleep() 休眠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28643998/

相关文章:

java - Thread.sleep 没有被 PowerMockito mock

c - 如何在 MPLAB C18 中使用内联汇编?

c - 为什么在 LinkedList 的这个实现中会出现段错误

c - "|\"是什么意思?

linux - 从父文件夹和所有子文件夹中删除特定的命名目录

linux - Linux 中的调度 : run a task when computer is idle (= no user input)

python - 多线程数据生成器

c - 使用指针数组时循环内存地址

regex - 从正则表达式中提取组

java - 重现线程干扰