I am just starting on how threading really works on linux (Ubuntu) using pthreads library. And I am stuck on first program. See the code first :
#include <pthread.h>
#include <iostream>
using namespace std;
void* th_func(void* arg) {
cout << "Indside Thread Start Routine !!n";
return NULL;
}
void foo() { cout << "Inside Foo !!n"; }
int main(void) {
int ret;
foo();
pthread_t thread;
if (!(ret = pthread_create(&thread, NULL, th_func, NULL))) {
cout << "ret = " << ret << endl;
}
return 0;
}
Simple compilation and test run of the program here 🙁 I intentionally use 0,1,… before $
just for the sake of indexing and trying to explain more efficiently )
0$ g++ t0.cpp
1$ ./a.out
Inside Foo !!
ret = 0
Indside Thread Start Routine !!
2$ ./a.out
Inside Foo !!
ret = 0
Indside Thread Start Routine !!
3$ ./a.out
Inside Foo !!
ret = 0
Indside Thread Start Routine !!
Indside Thread Start Routine !!
4$ ./a.out
Inside Foo !!
ret = 0
Indside Thread Start Routine !!
5$ ./a.out
Inside Foo !!
ret = 0
I am happy with all the test run except the run indexed with 3$. First let me share my understanding on the other run.
- At run 1$, 2$ and 4$, the main thread ended after the created thread ended resulting the
start routine
(function in this caseth_func
) to execute before program ends. - At run 5$ however the main thread ended before the created thread which causes created thread to terminate before code given to it processes. (
th_func
not printingcout
statement)
Let me come to the 3$ one which grabs all my attention or probably stuck in my head. My questions are :
- Why the created thread not terminated after printing whatever on
cout
statement and returningNULL
? (As DESCRIPTION section point no.2 suggests from man page of pthread_create:
DESCRIPTION top
The pthread_create() function starts a new thread in the calling
process. The new thread starts execution by invoking
start_routine(); arg is passed as the sole argument of
start_routine().The new thread terminates in one of the following ways:
It calls pthread_exit(3), specifying an exit status value that
is available to another thread in the same process that calls
pthread_join(3).It returns from start_routine(). This is equivalent to
calling pthread_exit(3) with the value supplied in the return
statement.It is canceled (see pthread_cancel(3)).
Any of the threads in the process calls exit(3), or the main
thread performs a return from main(). This causes the
termination of all threads in the process.
- If it returns the why print the statement of
cout
(cout << "Indside Thread Start Routine !!n";
) twice ? Is thread created twice ?
I put up my head on the internet for several hours but honestly could not find answer. Perhaps my code is not thread safe or idk ? I just could think may be pthread_join
help but still it just waits the created thread to be terminated and that won’t help my questions ( printing twice or maybe calling th_func
twice ). So I am wishing someone might help …
Thanks in advance 🙂
1