简体   繁体   中英

Windows C++ How can I call a blocking read from one thread to another?

I have two classes in C++ (Windows, Visual Studio 2010) each running a different thread, and I want to send messages between them in a simple way. The idea is that the main calls a read on class2, waits for class2 to get the data, and then main class receives it and continues - something like a socket, but between two class/thread on the same program. Can this be done?

Example:

class MyClass(){
    ...
    void run(){...}; //runs a thread here that collects data from a network socket
};



int main(){
    MyClass *mc = new MyClass();
    mc->run();
    ...
    mc->receiveData(); //returns a value AFTER the class gets a hold of it, and blocks in the meantime...
}

Is there any simple way to do this? Kind of like creating a socket, and reading from it, it won't return until it receives the packet/data from the network, except I want a class to do this on the local system. Thanks!

Create the thread and call a join() on the thread. (Google that). Thread joins will allow you to spawn off a thread for processing and indicate that once main reaches the join, it should wait for the thread it is joining to complete. You can return a value from the thread when it returns at the join statement so main can know the result if you need it.

Sounds like you want a thread-safe queue to put your messages on.

Check out the 'Parallel containers and objects' in the Microsoft Parallel Patterns Library . That page has an example showing the use of concurrent_vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM