使用C 中的线程并行计算
Parallel computing using threads in C++
我确实需要您的帮助。我需要在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::async
和std::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;
}
相关文章:
- 并行块(线程清理器)之外的 OpenMP 中的争用条件;误报?
- 我可以计算多线程数的平均值吗?
- System Verilog DPI - 在 cpp 中运行并行线程,在 SV 中运行另一个并行线程
- 是否可以限制C++17并行"for_each"的线程数
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- 如何从多个线程并行安全地访问和写入复杂容器?
- 为什么在某些特定情况下具有多个线程(并行处理)会降低性能
- 多线程蒙特卡罗计算中没有加速
- 使用C 中的线程并行计算
- 我遇到了一个关于多线程的小问题.需要多线程来计算 Pi 和方差
- 多个线程创建5个线程来计算质数
- C++STL多线程,并行运行计算
- Windows 线程:并行合并排序
- 使用哪个线程并行接口来使用堆栈进行任务共享和拆分
- c++:上下并行前缀计算的线程池
- 我如何在不同的核心上运行4个线程(并行)
- 调度大量线程,因此只有4个线程并行执行
- 从 Java 的多线程并行调用非线程安全的 DLL 函数
- 如何在CUDA线程内计算矩阵的指数
- CUDA如何获取网格、块、线程大小和并行化非方阵计算