使用C 中的线程并行计算

Parallel computing using threads in C++

本文关键字:线程 并行计算 使用      更新时间:2023-10-16

我确实需要您的帮助。我需要在C 中使用两个单独的线程来计算F(x)|| g(x)。程序应该看起来像下面列出的

#include <iostream>
#include <thread>  
using namespace std;
int f(int x);
int g(int x);
int main()
{
    cout << "Please enter an number" << endl;
    int x;
    cin >> x;
    thread first(f, x);
// Compute f(x)||g(x) using threads
// do something like this first||second
// Print result
}
int f(int x)
{
    int result = x;
    return result;
}
int g(int x)
{
    int result = x;
    return result;
}

如果您对解决此问题有任何想法,我将非常感谢。谢谢!

最好使用std::asyncstd::future解决此类问题,它可以使用线程,取决于您的使用方式。

int main() {
    std::cout << "Please enter an number" << std::endl;
    int x;
    std::cin >> x;
    auto f_future = std::async(std::launch::async, f, x);
    auto g_future = std::async(std::launch::async, g, x);
    //will block until f's thread concludes, or until both threads conclude, depending on how f resolves
    auto result = f_future.get() || g_future.get();
    std::cout << /*...*/ << std::endl;
}