Why are all of my threads sleeping using sleep()?

喜你入骨 提交于 2019-12-12 03:08:37

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/28646159/child-threads-sleeping-instead-of-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!