c++ - What is the best architecture to frequently communicate values between multiple threads? -


i writing application in c++14 consists of master thread , multiple slave threads. master thread coordinates slave threads coordinately perform search, each exploring part of search space. slave thread encounters bound on search. communicates bound master thread sends bound other slave threads can possibly narrow searches.

a slave thread must check whether there new bound available, possibly @ entrance of loop.

what best way communicate bound slave threads? can think of using std::atomic<int>, afraid of performance implications has whenever variable read inside loop.

the simplest way here imo not overthink this. use std::mutex each thread, protecting std::queue boundary information in. have main thread wait on std::condition_variable each child can lock, write "new boundary" queue , signals te cv, main thread wakes , copies value each child 1 @ at time. said in question, @ top of loops, child threads can check thread-specific queue see if there's additional bounding conditions.

you don't need "main thread" in this. have children write other children's queues directly (still mutex-protected), long you're careful avoid deadlock, work way too.

all of these classes can seen in thread support library, decent documentation here.

yes there's interrupt-based ways of doing things, in case polling relatively cheap because it's not lot of threads smashing on 1 mutex, thread-specific mutexes, , mutexes aren't expensive lock, check, unlock quickly. you're not "holding" on them long periods, , it's ok. it's bit of test really: need additional complexity of lock-free? if it's dozen (or less) threads, not.


Comments