C++ communication between threads

心已入冬 提交于 2019-12-29 06:43:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20595760/c-communication-between-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!