【发布时间】:2021-10-08 13:06:29
【问题描述】:
大家好,我在创建线程来填充数组时遇到了麻烦, 目标是使用 pthread 在尽可能快的时间内填充数组以显示并行化。
我正在尝试并行化这段代码以提高处理时间。
for (int i = 0; i < size; i++)
{
v3[i] = v1[i] + v2[i];
}
我已经尝试制作并行函数所需的基本准系统,但是我不确定下一步该从哪里开始。
我相信我需要创建另一个将数组填充到一定数量并并行调用它的函数,因此该函数的每个线程都会加快进程,但是由于我是 c++ 新手,我不确定如何这样做。
任何建议或资源将不胜感激。
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <chrono>
#include <pthread.h>
using namespace std::chrono;
using namespace std;
#define THREAD 8
struct arg_struct
{
int *v1, *v2, *v3;
unsigned long size;
};
int part = 0;
void randomVector(int vector[], int size)
{
for (int i = 0; i < size; i++)
{
//sets a random int value into the vector ith element position
vector[i] = rand() % 100;
}
}
void *parallel(void *arguments)
{
struct arg_struct *args = (struct arg_struct *)arguments;
unsigned long size = args->size;
int *v1 = args->v1;
int *v2 = args->v2;
int *v3 = args->v3;
int thread_part = part++;
for (int i = 0; i < size; i++)
{
v3[i] = v1[i] + v2[i];
}
}
void somefunction(void *arguments)
{
//
}
int main()
{
struct arg_struct args;
args.size = 100000000;
srand(time(0));
pthread_t threads[THREAD];
//int *v1, *v2, *v3;
//sets the clock to start by getting the time now
auto start = high_resolution_clock::now();
//memory alloc is used to dynamically allocate memory with the specified size.
args.v1 = (int *) malloc(args.size * sizeof(int *));
args.v2 = (int *) malloc(args.size * sizeof(int *));
args.v3 = (int *) malloc(args.size * sizeof(int *));
randomVector(args.v1, args.size);
randomVector(args.v2, args.size);
//ToDo: goes in a for loop that will append v3 ith value with v1 + v2
auto stop = high_resolution_clock::now();
for (int i = 0; i < THREAD; i++)
{
pthread_create(&threads[i], NULL, ¶llel, NULL);
}
pthread_join(threads[THREAD], NULL);
//gets the start and stop time and subtracts it to get the amount of time spent processing.
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
return 0;
}
【问题讨论】:
-
是否需要使用 pthread API?还是允许您使用更好的
std::threadAPI? -
欢迎来到 SO。请仅添加相关标签。您的代码不是有效的 C 代码。 C 和 C++ 是非常不同的语言。
-
考虑向每个 pthread 传递一个
args的副本,该副本在size和v1、v2和v3数组中具有不同的起点。 -
@Botje 我正在考虑这样做我只是无能为力
-
为什么是“无能”?你有 c++11 可用吗?
std::thread比 pthread 更容易使用
标签: c++ multithreading pthreads