Start thread once another is running
I start 3 pthreads and after running my application a few times I see that there is no exact order of the thread creation according to the order of the create statements.开发者_运维百科
How does one create another thread once a certain thread has started?
I still want to create the thread from the same "level" rather than creating the needed thread from inside the thread I want to start first.
Threads do not have "levels" or parent/child relationship. All threads including the initial thread main runs in are peers. Any thread can call pthread_join
on any other thread as long as the thread descriptor is valid and the thread is not detached.
If you do really need to enforce an ordering, the simplest tool for this is barriers (pthread_barrier_wait
). On the other hand, condition variables are a good bit more powerful, but harder to use, and probably not needed for this situation.
maybe you can find interesting pthread signals and wait on condition variables. Here are examples and the explanation. https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal
If your platform supports it, I belive semget(), semop(), semctl() should handle this. Just need to have the main process thread create and wait on a semaphore and have each thread semop() the semaphore once it is appropriate for the next thread in the sequence to be spawned.
See: http://support.sas.com/documentation/onlinedoc/sasc/doc700/html/lr2/z2101576.htm
Can you call call pthread_create() from the thread function?
pthread_create creates a thread, and as you have discovered, it doesn't call the thread function. Basically your new thread is on the active thread list and the scheduler can give it a timeslice whenever it chooses. Usually this is a couple ms, but can be longer.
精彩评论