C++,以并行和协作的方式运行两个函数

标签 c++ multithreading parallel-processing collaborative

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

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

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

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

最佳答案

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

您必须注意两个陷阱。

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

结果被覆盖。我通过在编写之前测试结果来做到这一点。

#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
}

关于C++,以并行和协作的方式运行两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002381/

相关文章:

android - 为什么 Android jvm->GetEnv() 会为多个线程返回相同的 "env"。?

c++ - 在 Recordset ADO 中找不到记录

c++ - 如何求解稀疏矩阵的线性方程 AX=b

c# - 如何根据最佳实践在 C# 4 中创建异步方法?

c++ - 使用 CUDA 并行化四个或更多嵌套循环

python - 如何从 multiprocessing.Pool.map 的worker_funtion内部为数组赋值?

c++ - 复制指向静态数组的指针

java - 单 Java 线程运行时的双核 CPU 利用率

java - 让 1 个线程等待一组线程完成

c# - "long-running tasks"是什么意思?