开发者

How can I check for the completion of threads without blocking?

开发者 https://www.devze.com 2023-02-17 16:24 出处:网络
I have a random number of threads being generated and my main thread needs to act as a timer in a tight loop. I would like to check if the children threads ended and if so I want to break the tight lo

I have a random number of threads being generated and my main thread needs to act as a timer in a tight loop. I would like to check if the children threads ended and if so I want to break the tight loop. However, I haven't been able to find any way to do this without blocking.

My best idea has been to use a variable equal to the random numbe开发者_C百科r of threads that will be created. When a thread is about to complete it should decrement the variable. Meanwhile the main thread can quickly check the variable to see if it is greater than 0, if so keep looping.

There must be a better way, I hope.


Does your main thread need to do anything else while it's waiting? In order to fully answer your question I need a better explanation of what you want to achieve, but here are some tools that might solve your problem:

  • Checking an ordinary variable on each loop iteration. You'll need to perform some locking primitive around the check to portably ensure a memory barrier, otherwise you might read an outdated value.
  • Signals. Ugly, but you could have the worker threads send a signal to the main thread with pthread_kill, and that could interrupt whatever it's doing. You'll have to deal with issues about what actions are async-signal-safe though (none of the pthread functions are).
  • Condition variables. You could use pthread_cond_wait (or pthread_cond_timedwait if you want to take some action after a given time interval if no threads have exited).
  • Semaphores. You could just use a semaphore as an atomic counter, or use it like a condition variable.


You could use either pthread_tryjoin_np or pthread_timedjoin_np which don't block, or have a timeout.

Read the man page for the exact semantics. These are Linux-specific though, non-portable as their name and the man pages state. So YMMV.

0

精彩评论

暂无评论...
验证码 换一张
取 消