funwithlinx funwithlinx - 9 months ago 40
Linux Question

Linux Multithreading - threads do not produce any output as expected

I am learning multi-threading in Linux platform. I wrote this small program to get comfort with the concepts. On running the executable, I could not see any error nor does it print

. Hence I made to sleep the thread after I saw the output. But still could not see the prints on the console.

I also want to know which thread prints at run time. Can anyone help me?

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

using std::cout;
using std::endl;

void* print (void* data)
cout << "Hi" << endl;

int main (int argc, char* argv[])
int t1 = 1, t2 =2, t3 = 3;
pthread_t thread1, thread2, thread3;
int thread_id_1, thread_id_2, thread_id_3;
thread_id_1 = pthread_create(&thread1, NULL, print, 0);
thread_id_2 = pthread_create(&thread2, NULL, print, 0);
thread_id_3 = pthread_create(&thread3, NULL, print, 0);
return 0;

Answer Source

Your main thread probably exits and thus the entire process dies. So, the threads don't get a chance to run. It's also possible (quite unlikely but still possible) that you'd see the output from the threads even with your code as-is if the threads complete execution before main thread exits. But you can't rely on that.

Call pthread_join(), which suspends the calling thread until the thread (specified by the thread ID) returns, on the threads after the pthread_create() calls in main():

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);

You can also use an array of pthread_t which would allow you to use a for loop over the pthread_create() and pthread_join() calls.

Or exit only the main thread using pthread_exit(0), which would exit only the calling thread and the remaining threads (the ones you created) will continue execution.

Note that your thread function should return a pointer or NULL:

void* print (void* data)
    cout << "Hi" << endl;
    return NULL;

Not sure about the high sleeps either right the threads exit, which is unnecessary and would hold the threads from exiting. Probably not something you wanted.