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);
print("Thread");
pthread_cleanup_push(handler, "hello");
pthread_cleanup_pop(1);
printf("Thread Done\n");
return (void *) 0;
}
int main(void)
{
pthread_t tid1, tid2;
void *tret;
if(pthread_create(&tid1, NULL, thread_function1, (void *)1))
exit(1);
if(pthread_create(&tid2, NULL, thread_function1, (void *)2))
exit(1);
// 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. If both the comments are removed then thread 2 is executed only after thread 1 has completeted its execution.
What I want to do is have thread 1 and thread 2 execute simultaneously and main should wait for completion of both the threads.
thread_function1finishes before the second thread is even created?