I'm trying to understand how multithreading works. I've written the following code
void handler(void *arg)
printf("Printf from cleanup handler: %s\n", (char*)arg);
void print(const char *msg)
printf("%7s: Pid=%d Tid:%lu\n", msg, getpid(), pthread_self());
void* thread_function1(void *args)
printf("Received: %d\n", (int)args);
return (void *) 0;
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, thread_function1, (void *)1))
if(pthread_create(&tid2, NULL, thread_function1, (void *)2))
// pthread_join(tid2, &tret);
// pthread_join(tid1, &tret);
The problem with this code is that the main completes its execution before thread_function1 could complete its execution.
That's because when the main thread exits, the process dies including all threads. You can instead call
pthread_exit(0) from the main thread so that the rest of the threads continue execution and the main thread exits.
If both the comments are removed then thread 2 is executed only after thread 1 has completeted its execution.
That's not true. i.e.
tid2 are executed simultaneously after they are created ("simultaneous execution" depends on your hardware, scheduling policy etc -- but as far as you program is concerned, they can be considered as being executed simultaneously).
pthread_join() doesn't control the order of threads' execution. It only affects the order in which the main thread waits for the completion of the threads i.e. main thread waits for
tid2 to complete first and then waits for
tid1 (if you ncomment those two lines).