4

Im using Ubuntu 10.10, Code::Blocks with GCC 4.2.

I have written a code like that:

#include <iostream>
#include <stdlib.h>
#include <pthread.h>

using namespace std;

void *thread1proc(void* param){
    while(true)
    cout << "1";

    return 0;
}

int main(){
    pthread_t thread1;

    pthread_create(&thread1,NULL,thread1proc,NULL);
    pthread_join(thread1,NULL);

    cout << "hello";
}

Main starts, creates the thread. But what is weird (for me) is main doesn't continue running. I expect to see "hello" message on screen and end of the program. Because in Windows, in Delphi it worked for me like that. If "main" is also a thread, why doesn't it continue running? Is it about POSIX threading?

Thank you.

1
  • For portability, explicitly create threads in a joinable state with pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) Dec 6, 2010 at 20:27

2 Answers 2

8

pthread_join will block until thread1 completes (calling pthread_exit or returning), which (as it has an infinite loop) it never will do.

0
3

It stops because you call pthread_join and the thread you are joining "to" has an infinite loop.

From that link:

The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated.

4
  • @Tolga: You can fire as many threads as you'd like. In your specific case, you'd have to fire them up before the call to pthread_join, because your thread hangs in an infinite loop. You need to study how the pthread library works... See here: computing.llnl.gov/tutorials/pthreads Dec 6, 2010 at 21:41
  • @Tolga: pthreads and windows threads work fairly similarly. Windows does not, however, have an equivalent to the join function ...
    – Goz
    Dec 6, 2010 at 21:43
  • Isn't there any function like "resumeThread" as in Windows APIs? I don't want tp wait for end of thread.
    – tcak
    Dec 6, 2010 at 21:55
  • Ok. I ve found the solution. I didn't use pthread_join function. I substituted while(true){}. And it looks thread continues working. I supposed, we needed pthread_join function to start the thread. Thank you.
    – tcak
    Dec 6, 2010 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.