c++ - 使用并行线程查找加到给定数字的所有组合
问题描述
问题是找到一种方法来达到与下面代码中已经达到的结果相同的结果,但要使用自定义数量的线程,使用临界区和信号量,以便并行化下面的代码
我试图并行化代码的递归部分,但我没有想出任何合理的解决方案
代码可以在这里以某种方式并行化,信号量可用于并行化代码,但尚不清楚哪些部分可以并行运行
已经运行的解决方案:
C ++程序找出加到给定数字的所有正数组合
#include <iostream>
using namespace std;
// arr - array to store the combination
// index - next location in array
// num - given number
// reducedNum - reduced number
void findCombinationsUtil(int arr[], int index,
int num, int reducedNum)
{
// Base condition
if (reducedNum < 0)
return;
// If combination is found, print it
if (reducedNum == 0)
{
for (int i = 0; i < index; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
// Find the previous number stored in arr[]
// It helps in maintaining increasing order
int prev = (index == 0)? 1 : arr[index-1];
// note loop starts from previous number
// i.e. at array location index - 1
for (int k = prev; k <= num ; k++)
{
// next element of array is k
arr[index] = k;
// call recursively with reduced number
findCombinationsUtil(arr, index + 1, num,
reducedNum - k);
}
}
找出加到给定数字的所有正数组合的功能。它使用 findCombinationsUtil()
void findCombinations(int n)
{
// array to store the combinations
// It can contain max n elements
int arr[n];
//find all combinations
findCombinationsUtil(arr, 0, n, n);
}
驱动程序代码
int main()
{
int n = 5;
findCombinations(n);
return 0;
}
来源:https ://www.geeksforgeeks.org/find-all-combinations-that-adds-upto-given-number-2/
解决方案
我将引用另一个答案中的一句话:
我会走建议路线。在尝试使用线程使您的程序更快之前,您首先要使其在单线程情况下更快。
在你的具体问题中,我认为并行化函数有点困难。例如,您可以让每个线程在原始数组的子数组中找到数字的组合,但是不同子数组中的组合呢?显然,并行化这个问题是有限制的,因为每个数字都依赖于其他数字。您可以在进行并行计算之前预先缓存总和,但如果您想要形成组合的数字,它不会有太大帮助。
有关更多信息,请参阅这些链接。
https://www.codeproject.com/Articles/1247260/Cplusplus-Simple-Permutation-and-Combination-Paral
推荐阅读
- django - NGINX-WSS 连接失败但 WS 连接有效
- python - 你如何用“with”这个词发出命令
- python - 在 Python 中创建和修改包级变量
- python - 在 3D 空间中绘制 2D 图像
- php - 如何在 Debian Stretch 中安装新的 php 库?
- javascript - Expo Android 的时区问题
- rust - 为包含可迭代字段的结构实现迭代器特征
- c# - 将 Picker ItemSource 绑定到列表
不工作 Xamarin.forms MVVM - deep-learning - 从预训练的检查点 (.bin) 加载层的输出
- python - 在 Python 中使用 for 循环绘图