Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

multithreading - C++ communication between threads

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...