1

我有两个要并行执行的方法,数据通过 const 引用传递。

一旦其中一个方法完成了它的工作,另一个方法就没有必要继续了,因为其中一个方法的执行时间可能很长,具体取决于条目,因此必须停止。

我发现我可以通过使用<thread>标头运行两个线程来并行执行这两种方法,但是在加入它们之后我必须等待这两种方法完成。

我如何使用这种协作机制实现这种类型的并行处理?

4

1 回答 1

4

我写了一个小样本来展示它是如何完成的。正如您已经发现的那样,它不能通过 join 归档。当它有结果时,您需要一个可以从线程发出信号的事件。为此,您必须使用std::conditon_variable. 该示例显示了您所描述问题的最小可能解决方案。在示例中,结果很简单。

您必须注意两个陷阱。

a.线程在 main 等待之前完成。出于这个原因,我在启动线程之前锁定了互斥锁。

湾。结果被覆盖。我通过在编写结果之前测试结果来管理它。

#include <thread>
#include <condition_variable>
#include <mutex>

std::mutex mtx;
std::condition_variable cv;

int result = -1;

void thread1()
{
    // Do something
    // ....
    // ....

    // got a result? publish it!
    std::unique_lock<std::mutex> lck(mtx);
    if (result != -1)
        return; // there is already a result!

    result = 0; // my result
    cv.notify_one(); // say I am ready
}

void thread2()
{
    // Do something else
    // ....
    // ....

    // got a result? publish it!
    std::unique_lock<std::mutex> lck(mtx);
    if (result != -1)
        return; // there is already a result!

    result = 1; // my result
    cv.notify_one(); // say I am ready
}

int main(int argc, char * argv[])
{
    std::unique_lock<std::mutex> lck(mtx); // needed so the threads cannot finish befor wait
    std::thread t1(thread1), t2(thread2);

    cv.wait(lck); // wait until one result

    // here result is 0 or 1;

    // If you use the loop described below, you can use join safely:
    t1.join();
    t2.join();
    // You have to call join or detach of std::thread objects before the
    // destructor of std::thread is called. 

    return 0;
}

如果你想在一个已经有结果的情况下停止另一个线程,唯一合法的方法是在两个线程中频繁测试结果,如果有人已经有结果,则停止。在这种情况下,如果您使用指针或泛型类型,则应使用volatile修饰符对其进行标记。如果您必须在循环中工作,线程函数的外观如下:

void thread1()
{
    // Do something
    bool bFinished=false;
    while(!bFinished)
    {
      { // this bracket is necessary to lock only the result test. Otherwise you got a deadlock a forced sync situation.
        std::unique_lock<std::mutex> lck(mtx);
        if (result != -1)
           return; // there is already a result!
      }         
      // do what ever you have to do
    }

    // got a result? publish it!
    std::unique_lock<std::mutex> lck(mtx);
    if (result != -1)
        return; // there is already a result!

    result = 0; // my result
    cv.notify_one(); // say I am ready
}
于 2015-05-02T13:07:15.010 回答