Reputation: 2494
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!
Upvotes: 0
Views: 231
Reputation: 859
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
.
Upvotes: 0
Reputation: 39304
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.
Upvotes: 1