开发者

Boost: how deal time dependent thread operations?

For example ha开发者_JS百科ving an array or reader threads and one writer thread we can sinc tham like this via shared_mutex and shared_lock this works if we are not dependent on time. But if we want to get all writing operations done inside of certan time frame and if thay are not done stop waiting and start doing something else inside of reader threads. How to do such thing? How to be capable to say from some watcher thread to all readers threads - "hey guys - there wount be any new data from writer in this time frame so go on."


Use a timed lock.

boost::shared_mutex  m

Reader()
 shared_lock   lock(m, timeout);
 if(!lock) {
   //I don't have the lock. Don't touch the resource and do something else.
 }
 else {
   //I have the lock. Read now.
 }

Writer()
 upgrade_lock lck(m);
 upgrade_to_unique_lock uniqueLock(lck);

Just pick a timeout value. Note that it won't necessarily be precise.

BTW: if you're going to use Boost.Threads, perhaps you should read the documentation. It's pretty extensive. I've never used Boost.Threads, and it took me a matter of seconds to find this.


There's an alternative way of going about your problem: check out the Thread Pool pattern. With this pattern, you divide up the work into units that can be executed by a pool of worker threads. Whenever there's something to do, you queue up a work unit, and the next available thread in the pool will execute it. This insures that threads are always busy doing something (when there is something to do).

You will need to learn about thread-safe producer-consumer queues to implement this pattern.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜