2014-12-03 70 views
0

尝试使此函数正常工作时出现错误。我在写一个并行合并排序函数。错误是我似乎无法弄清楚如何传递一个向量到pthread_create函数。我似乎无法弄清楚如何传递有关向量的所有信息,以便并行mergesort可以工作,但仍然可以将其转换为void *,以便我可以将它作为pthread_create函数的参数传递。使用pthreads似乎无法通过pthread_create函数传递向量

`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

我想出了“不能将pthread_t *和pthread_t中的线程[0]'转换为pthread_t的问题。”我需要拿出'&'号。然而,pthread_create函数仍然给我一些问题。 – user3088470 2014-12-03 14:58:54

+1

我建议您阅读您最喜欢的书中关于指针的章节。 – molbdnilo 2014-12-03 15:01:45

+1

@ user3088470你能编辑你的代码来发布一个自编的例子吗(参见http://sscce.org/)? – 2014-12-03 15:09:37

回答

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; 
} 

如果你通过了,作为一个线程的说法,一个指针,指向具有自动存储时间的变量,要小心,并确保在范围变量停留在至少只要线程可以访问它。