尝试使此功能正常工作时出错。我正在写一个并行合并排序功能。错误是我似乎无法弄清楚如何将向量传递给pthread_create函数。我似乎无法弄清楚如何传递有关向量的所有信息,以便并行mergesort可以工作,但仍然将其转换为void *,以便我可以将其作为pthread_create函数的参数传递。 / p>
`void parallel_mergesort(void * a) {`
//std::vector<int> v = (std::vector<int>) * a;
vector<int>* v = static_cast<vector<int>*>(a);
int mid = v->size()/2;
pthread_t threads[2];
int count;
std::vector<int> * v1;
std::vector<int> * v2;
int start = 0;
int end = 0;
for (int i =0; i < mid; i++)
{
v1[i] = v[i];
start = i;
}
for (int j = 0; j < v->size(); j++)
{
v2[j] = v[j+mid];
end = j + mid;
}
if (start >= end) return;
count = pthread_create(threads[0], NULL, parallel_mergesort, (&v1));
if (count) {
printf("unable to create thread");
exit(1);
}
count = pthread_create(threads[1], NULL, parallel_mergesort, &v2);
if (count) {
printf("unable to create thread");
exit(1);
}
pthread_join(&threads[0], NULL);
pthread_join(&threads[1], NULL);
//merge(..
pthread_exit(NULL);
}
int main()
{
std::fstream infile("data.txt", std::ios_base::in);
std::fstream outfile_pms("parallelmergesorted.txt", std::ios_base::out);
std::vector<int> parallel_mergesorted = vals;
parallel_mergesort(parallel_mergesorted);
for(std::vector<int>::iterator it = parallel_mergesorted.begin(); it != parallel_mergesorted.end(); ++it) {
outfile_pms << *it << std::endl;
}
}
答案 0 :(得分:0)
这个想法是你将参数绑定(指针)到pthread_create
的第四个参数。当然后启动线程时,参数被绑定到线程的启动例程的参数。
这是一个简单的例子:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
/* start routine of the thread */
void *task(void *data)
{
char *s = data; /* cast argument to the appropriate type */
puts(s);
return NULL;
}
/* entry point of the application */
int main(void)
{
char *s = "Hello, world!\n";
pthread_t t;
pthread_create(&t, NULL, task, s); /* pass argument to thread */
pthread_join(t, NULL);
return EXIT_SUCCESS;
}
如果作为线程参数传递指向具有自动存储持续时间的变量的指针,请小心并确保该变量至少在线程可以访问它的范围内保留。