Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple threads in C program

I'm writing a Unix application in C which uses multiple threads of control. I'm having a problem with the main function terminating before the thread it has spawned have a change to finish their work. How do I prevent this from happening. I suspect I need to use the pthread_join primitive, but I'm not sure how. Thanks!

like image 389
gamma4332 Avatar asked Nov 08 '09 02:11

gamma4332


People also ask

What is multi threading in C?

Multithreading is a model of program execution that allows for multiple threads to be created within a process, executing independently but concurrently sharing process resources. Depending on the hardware, threads can run fully parallel if they are distributed to their own CPU core.

How many threads are there in C program?

It is 6 - one per core. Many CPU:s have hyperthreading which gives them 2 threads per core. Yours don't. I wouldn't mix in processes here but yes, only one thread can run at the same time in one of your i5-8400 cores.

What is multiple threading with example?

What is MultiThreading? Multithreading enables us to run multiple threads concurrently. For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed. So multithreading improves the responsiveness of a system.

When should I use multiple threads?

Multithreading is used when we can divide our job into several independent parts. For example, suppose you have to execute a complex database query for fetching data and if you can divide that query into sereval independent queries, then it will be better if you assign a thread to each query and run all in parallel.


2 Answers

Yes, you could use pthread_join() (see other anwers for how to do that). But let me explain the pthread model and show you another option.

In Unix, a process exits when the primary thread returns from main, when any thread calls exit() or when the last thread calls pthread_exit(). Based on the last option, you can simply have your main thread call pthread_exit() and the process will stay alive as long as at least one more thread is running.

like image 119
R Samuel Klatchko Avatar answered Oct 10 '22 13:10

R Samuel Klatchko


Yes one of doing this is to use pthread_join function: that's assuming your thread is in "joinable" state.

  • pthread_create: after this function returns control, your thread will be executing your thread function.

  • after pthread_create, use the tid from pthread_create to pthread__join.

If your thread is detached, you must use some other technique e.g. shared variable, waiting on signal(s), shared queue etc.

Great reference material available here.

like image 21
jldupont Avatar answered Oct 10 '22 13:10

jldupont