Ibrahim Ibrahim - 1 month ago 13
C Question

Concurrent Multithreading

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.

usr usr
Answer

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. tid1 and 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).