Well, in a multi-process application you would be using pipes/files to transmit information from one process to another (or even maybe the return value of a child process). So could also try shared memory, though it can be somewhat challenging (look into Boost.Interprocess if you wish to).
In a multi-threaded application you basically have the same options available:
- you can use memory that is shared (provided you synchronize access)
- you can use queues to pass information from one thread to another (such as with pipes)
so really the two are quite similar.
Following Tony Hoare's precept, you should generally share by communicating, and not communicate by sharing, which means privileging queues/pipes to shared memory; however for just a boolean flag, shared memory can prove easier to put in place:
void do_a(std::atomic_bool& done) {
// do things
done = true;
}
int main() {
std::atomic_bool done = false;
auto a = std::async(do_a, done);
auto b = std::async([](std::atomic_bool& done) {
while (not done) {
std::cout << "still not done" << std::endl;
sleep(1);
}
});
// other stuff in parallel.
}
And of course, you can even put this flag in a std::shared_ptr
to avoid the risk of dangling references.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…