Reputation: 4864
I have a couple classes that each open a different program in different threads and do/hold information about it using CreateProcess
(if there's a more C++ oriented way to do this let me know-- I looked).
Some of the classes are dependent on one of the other programs running. ie B must stop if A stopped. I made this code a while ago and my solution then, was having a class with static functions that run the various programs and static member variables that hold their "state". I was also using CreateThread
.
Looking back, this method seemed... fragile and awkward looking.
I have no idea if using such a "static class" is good practice or not (especially recalling how awkward initializing the state member variables). I'd like to perhaps make each class contain its own run function. However, the issue I am considering is how to let class B know if A has awkwardly stopped. They'd still need to know a way to be aware of each other's state. Note that I'd like to use std::thread
in this rework and that I have little to no experience with multithreading. Thanks for any help.
Upvotes: 15
Views: 40301
Reputation: 299730
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:
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.
Upvotes: 12