为什么我的所有线程使用睡眠()睡觉? [英] Why are all of my threads sleeping using sleep()?

查看:393
本文介绍了为什么我的所有线程使用睡眠()睡觉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到关于网络上的线程在Linux下面的一段code的。但是,当我运行它,所有的线程似乎睡觉,而不是只在主线程。为什么?此外,不睡觉(5),该陈述书成功创建线程运行3次,而不是2?是否有人可以解释这种现象?谢谢
使用编译:
GCC -pthread check.c

和我的O / P:
第一个线程processingn
线程创建successfullyn
第二个线程processingn
线程创建successfullyn

前两行印有5秒的滞后,未来2后5秒多。为什么子线程得到睡的主要原因呢?

 #包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&pthreads.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;
的pthread_t TID [2];无效* DoSomething的(){
    无符号长I = 0;
    的pthread_t ID = pthread_self();    如果(pthread_equal(ID,TID [0]))
    {
        的printf(\\ n个第一线processingn);
    }
    其他
    {
        的printf(\\ N次线程processingn);
    }
    返回NULL;
}
INT主要(无效)
{
    INT I = 0;
    INT犯错;
    而(ⅰ2)
    {
        ERR =在pthread_create(及(TID [I]),NULL,&安培; DoSomething的,NULL);
        睡眠(5);
        如果(ERR!= 0)
            的printf(\\ ncan't创建线程[%S]字符串错误(错误))
            其他                的printf(\\ n主题创建successfullyn);
        我++;
        //睡眠(5);
    }
    在pthread_join(TID [0],NULL);
    在pthread_join(TID [1],NULL);    返回0;
}


解决方案

为什么你觉得所有的线程都睡着了吗?看了一些 pthread的教程&安培; 的pthreads(7)

它看起来像你的线程很快终止。你应该也加入其中(如前睡眠,或内部某处)使用的在pthread_join(3)

 的for(int i = 0;我2;我++){
    无效* RETVAL = NULL;
    在pthread_join(TID [I],和放大器; RETVAL);
    //你的情况,因为DoSomething的给NULL:
    断言(RETVAL == NULL);
 }

或你应该有超脱创建线程,请参见在pthread_create(3)&安培;例如,在 pthread_attr_init(3)&安培; pthread_attr_setdetachstate(3)等...

如果您还有codeD(因为你期望的DoSomething 获得 NULL 参数):

 无效* DoSomething的(无效* ARG){
   断言(ARG == NULL);

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

您或许应该的 fflush(3) 是在适当的地方(因为标准输入输出(3)往往是缓冲),例如:叫 fflush(NULL); 的DoSomething年底

阅读未定义行为并努力避免它。

这是做重要 fflush(NULL); 里面从中输出(至少在结束之前)预计线程。你的问题是不相关的睡眠但缓冲。和的printf 经常缓冲,非常有效的性能的原因。而且你也应该采取的习惯,结束的printf 格式控制字符串\\ n (因为经常刷新缓冲区)。把一个 \\ n 仅在的printf 格式字符串的开头是个坏习惯(这应该是在年底)。


顺便说一句,用无效ARG 修正无效* DoSomething的(无效* ARG)行(因为给出在你的问题的原始版本的code甚至不编译)我遵守以下的输出在编译:

 %的gcc -Wall -g x.c -pthread -o XX
   x.c:在功能DoSomething的:
   x.c:11:19:警告:未使用的变量'我'[-Wunused变量]
        无符号长I = 0;
                      ^

然后执行:

 %./xx   线程创建成功   第一个线程处理   线程创建成功   第二个线程处理

因此​​,在这个问题给出的code不我的电脑上表现为在这个问题解释。因此恶劣S. Kulshrestha 应给予的确切的源$编辑他的问题C $ C,完整的编译命令,而确切的输出。 FWIW,我的系统是Linux /于Debian /希德上的x86-64, GCC 是4.9.2版本,的libc 是Debian的GLIBC 2.19-15

I saw the following piece of code regarding threading in Linux on the web. But when I run it, all the threads seem to sleep instead of just the main thread. Why? Also, without sleep(5), the statement-"Thread created successfully" runs 3 times instead of 2? Can someone please explain this behavior? Thanks Compiled using: gcc -pthread check.c

and my o/p: First thread processingn Thread created successfullyn Second thread processingn Thread created successfullyn

The first two lines are printed with a lag of 5sec and the next 2 after 5 more sec. Why are the child threads getting slept instead of the main?

#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;
}

解决方案

Why do you think all your threads are sleeping? Read some pthreads tutorial & pthreads(7)

It looks like your threads are very quickly terminated. You should have joined them (e.g. before the sleep, or somewhere inside main) using pthread_join(3)

 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); 
 }

or you should have created detached threads, see pthread_create(3) & example in pthread_attr_init(3) & pthread_attr_setdetachstate(3) etc....

And you should have coded (since you expect doSomeThing to get a NULL argument):

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

BTW, please compile with gcc -Wall -Wextra -g and learn how to use the gdb debugger.

You probably should call fflush(3) at appropriate places (because stdio(3) is often buffered), e.g. call fflush(NULL); at the end of doSomeThing

Read about undefined behavior and work hard to avoid it.

It is important to do fflush(NULL); inside threads from which you expect output (at least before ending them). Your question is not related to sleep but to buffering. And printf is often buffered, for very valid performance reasons. And you should also take the habit to end printf format control string with \n (since that is often flushing the buffer). Putting an \n only at the beginning of a printf format string is a bad habit (it should be at the end).


BTW, by correcting the void* doSomething(void*arg) line (since with void arg as given in the original version of your question the code does not even compile!) I observe the following output at compilation:

 % 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;
                      ^

then executing with:

   % ./xx

   Thread created successfully

   First thread processing

   Thread created successfully

   Second thread processing

So the code given in the question does not behave on my computer as explained in the question. Therefore Harsh S. Kulshrestha should edit his question by giving the exact source code, the complete compilation command, and the exact output. FWIW, my system is a Linux/Debian/Sid on x86-64, gcc is version 4.9.2, libc is Debian GLIBC 2.19-15

这篇关于为什么我的所有线程使用睡眠()睡觉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆