Windows C++如何调用从一个线程到另一个线程的阻塞读取?

发布于 2024-11-30 11:25:15 字数 582 浏览 1 评论 0原文

我有两个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月无声 2024-12-07 11:25:15

创建线程并在线程上调用 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.

著墨染雨君画夕 2024-12-07 11:25:15

听起来您想要一个线程安全的队列来放置消息。

查看 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文