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!
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- How to let a thread communicate with another activ
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
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.
Check this simple C code I wrote for one of my libraries
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 topthread__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.
You may want to look at this page: http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/apis/users_25.htm
There are a number of different ways you can do this, but the simplest is to call
pthread_exit()
before returning frommain()
.Note that this technique works even if the thread you want to wait for is not joinable.