Windows C++如何调用从一个线程到另一个线程的阻塞读取?
我有两个 C++ 类(Windows、Visual Studio 2010),每个类运行不同的线程,我想以一种简单的方式在它们之间发送消息。这个想法是,main 调用 class2 上的读取,等待 class2 获取数据,然后主类接收它并继续 - 类似于套接字,但在同一程序的两个类/线程之间。这可以做到吗?
示例:
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...
}
有什么简单的方法可以做到这一点吗?有点像创建一个套接字并从中读取,直到它从网络接收到数据包/数据时它才会返回,除非我想要一个类在本地系统上执行此操作。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建线程并在线程上调用 join()。 (谷歌那个)。线程连接将允许您生成一个线程进行处理,并指示一旦 main 到达连接,它应该等待它正在连接的线程完成。当线程在 join 语句处返回时,您可以从线程返回一个值,这样 main 就可以在需要时知道结果。
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.
听起来您想要一个线程安全的队列来放置消息。
查看 Microsoft 并行模式库中的“并行容器和对象” 。该页面有一个示例,展示了 concurrent_vector 的使用。
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
.