Posix thread main C ++ question

Hi guys, I have a question about some code that I am testing to begin to understand posix streams.

I have this base code:

#include <iostream> #include <string> #include <sstream> #include <pthread.h> using namespace std; void *printInfo(void *thid){ long tid; tid =(long)thid; printf("Hello from thread %ld.\n",tid); pthread_exit(NULL); } int main (int argc, char const *argv[]) { int num =8; pthread_t threadlist[num]; int rc; long t; for(t=0;t<num;t++){ printf("Starting thread %ld\n",t); rc = pthread_create(&threadlist[t],NULL,printInfo,(void *)t); if(rc) { printf("Error creating thread"); exit(-1); } } pthread_exit(NULL); return 0; } 

Very simple code, starting threads and printing from them, everything works wonders, except that I do not understand the last pthread_exit (NULL) before returning 0; at the end of the main method.

It seems that the main thread should not be pthread, and it does not need this! If I don’t say it, the code does not work (this means that the code is compiled and executed, but I only receive messages "start thread" hte "start thread", and not messages "hello from ..".

So basically I want to know why this is needed.

In addition, the code compiles and runs correctly if I comment on include

+4
source share
3 answers

If you do not use pthread_exit in the main function, then all created threads terminate as main finishes, i.e. in your case, before they print anything.

By calling pthread_exit in the main function, main pauses all threads.

On the pthread_exit man page:

The process will terminate with a final state of 0 after the end of the last thread. The behavior looks as if the implementation was called exit () with a null argument at the time that the stream ended.

This refers to calling pthread_exit () from the main process thread.

+4
source

pthread_exit will only terminate the main thread, but will allow other threads to work until they finish their work. If you return from main or call exit , it will kill all threads.

+2
source

You need to join your topics. What happens without pthread_exit is that you started the threads, and then the main outputs, before it actually started any of the threads. When main exits, the program stops working (like threads).

Generally, you should use pthread_join , which waits until the specified thread completes execution.

It seems that pthread_exit makes main wait for all threads that I did not know about. However, I would look into this because it is not in the documentation (as far as I read in any case), and perhaps you should not rely on it.

Edit: also in your case you don't need to use pthread_exit . The thread automatically stops when the executed function returns ( printInfo in your case). pthread_exit allows you to terminate a thread before an executable function is executed, for example, if the executable function calls another function that calls pthread_exit .

+1
source

Source: https://habr.com/ru/post/1343789/


All Articles