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

随声附和 提交于 2019-12-02 09:21:19
Basile Starynkevitch

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

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