简体   繁体   English

改善多线程通信?

[英]Improve multi thread communication?

Here is the code on thread #1: 这是线程#1上的代码:

move = false;
//start thread #2
while(!move) Sleep(5);
//do stuff

Thread #2 code: 线程2代码:

//do stuff
move = true;

Is there a better way to wait for the change of move, for example, doing what is called block till data are read in networking? 是否有更好的方法来等待移动的变化,例如,在网络中读取数据之前执行所谓的阻止操作?

Using C++11? 使用C ++ 11? Use std::condition_variable. 使用std :: condition_variable。

What you have is a way. 你拥有的是一种方法。

There other things you can use. 还有其他可以使用的东西。 A few come to my mind: 我想到了一些:

Using conditions 使用条件

A condition is somewhere where you can wait() for other part (thread) of the code to signal() you can continue 条件是您可以在其中等待代码的其他部分(线程) 发出信号(可以继续)的条件

Conditions are associated to a mutex 条件与互斥锁相关

In your code: 在您的代码中:

Thread #1 线程#1

// start thread #2
mutex.acquire();
// You could check for an actual condition here if it
// is more complex than a true false.
condition.wait();
// If we're checking for a complex condition here
// we should re-evaluate in case it is not satisfied.
mutex.release();

Thread #2 线程#2

// do stuff
mutex.acquire();
condition.signal();
mutex.release();

Using a Future 使用未来

A Future is a higher level construct for representing the result of an asynchronous operation. Future是用于表示异步操作结果的更高级别的构造。

It works more or less like this: 它或多或少是这样的:

  1. The caller creates a Future object and keeps a reference to it and passes a reference to the thread performing the asynchronous operation. 调用者创建一个Future对象并保留对其的引用,并将引用传递给执行异步操作的线程。
  2. The caller continues its processing while the other thread performs its task. 调用方继续其处理,而另一个线程执行其任务。
  3. If the caller needs the result, it will try to get it from the Future object. 如果调用方需要结果,它将尝试从Future对象获取结果。 If the result it is not yet available, the caller will be blocked (eg using a condition/signal) until the asynchronous operation finishes and sets the value (that sends the signal). 如果结果尚不可用,则将阻止调用方(例如,使用条件/信号),直到异步操作完成并设置值(发送信号)为止。
  4. If the asynchronous operation finishes before it is needed, the caller will get the result without wait. 如果异步操作在需要之前完成,则调用者将立即获得结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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