funwithlinx funwithlinx - 1 year ago 82
C++ Question

Linux Multithreading

I am learning multithreading 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.

Call pthread_join() on the threads after the pthread_create() calls in main():

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

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

Note 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.