【发布时间】:2012-12-13 13:18:11
【问题描述】:
所以我们正在努力应对挑战,我们需要并行化 c++ 代码,以确保它使用多个内核而不是一个内核。我们为此使用了 openmp,它现在运行得更好了。但对于另一部分,我们需要使用 pthread。由于我们对 C++ 非常陌生(实际上这是我们第一次使用它),因此我们很难让线程正常工作。
这是原始代码的简约版本:
int main(int argc, char **argv) {
...code ...
//These 2 functions should be running in parallel
work_calculation(flights, parameter, alliances);
play_calculation(flights, parameter, alliances);
...code...
}
void work_calculation(vector<Flight>& flights, Parameters& parameters, vector<vector<string> >& alliances)
{
... code ...
do_calculation(flights, parameters, alliances);
... code ...
}
void do_calculation(vector<Flight>& flights, Parameters& parameters,
vector<vector<string> >& alliances)
{
...code...
}
为了将 pthread 与具有多个参数的函数一起使用,我们发现我们需要使用结构体。所以我们想出了这个:
int main(int argc, char **argv) {
...code ...
s_param parathread;
parathread.flights = flights;
parathread.parameters = parameters;
parathread.alliances = alliances;
pthread_t play;
pthread_t work;
pthread_create(&play, NULL, work_calculation ,¶thread);
pthread_create(&work, NULL, play_calculation, ¶thread);
pthread_join(play, NULL);
pthread_join(work, NULL);
...code...
}
typedef struct
{
vector<Flight> flights;
Parameters parameters;
vector<vector<string> > alliances;
} s_param;
void* work_calculation(void* args)
{
... code ...
struct s_param *paraThread = (struct s_param*)args;
do_calculation(paraThread->flights, paraThread->parameters, paraThread->alliances);
... code ...
pthread_exit(NULL);
}
void do_calculation(vector<Flight>& flights, Parameters& parameters,
vector<vector<string> >& alliances)
{
...code... (same as original)
}
如果我们这样做,我们会得到以下错误:
错误:不允许指向不完整类类型的指针 -> 在我做 paraThread 的任何地方
我们也尝试过在 struct s_pram *paraThread = (struct s_param*)args => 中不使用结构(所以像这样: s_param *paraThread = args; ,但是我们在编译时遇到了这些错误:
标识符 s_param 未定义且 标识符 paraThread 未定义
我们做错了什么?希望有人能帮我们定位问题。
【问题讨论】:
-
无关,但你考虑过Boost吗?
-
work_calculation是否具有s_param的可见性?即它们是否在与s_param首先声明的同一源文件中?还是在包含work_calculation的源文件包含的标头中声明了s_param?
标签: c++ pointers struct pthreads