使用vector <pthread_t> :: iterator创建和连接pthread

时间:2016-04-26 20:26:12

标签: c++ pointers vector pthreads pthread-join

使用线程处理一个简单的项目以计算多个txt文件。我在编译中遇到的唯一错误涉及vector<pthread_t>::iterator循环中使用pthread_join

错误是:

error: invalid conversion from long unsigned int* to pthread_t {aka long unsigned int} [-permissive]}
`pthread_join(&*iter, (void**)&returnValue);` <--

以下是相关代码:

vector<string> voteTallyFiles;
vector<voteTally> intermVoteTallies;
tallyArgs *pThreadArgs;
void *returnValue;
int index = 0;

getFileNames(VOTE_TALLY_DPATH, voteTallyFiles);

vector<pthread_t> threads(voteTallyFiles.size());

for (vector<pthread_t>::iterator iter = threads.begin(); iter != threads.end(); ++iter, index++)
{
    pThreadArgs->fName = voteTallyFiles[index];
    pthread_create(&*iter, NULL, countVotes, pThreadArgs);
}

for (vector<pthread_t>::iterator iter = threads.begin(); iter != threads.end(); ++iter)
{
    pthread_join(&*iter, (void**)&returnValue);
    intermVoteTallies.push_back((voteTally)returnValue)
}

我已经仔细阅读了pthread和pthread_join的文档,并且认为我已经正确地跟踪了所有指针/引用/参考,但显然我错过了某些地方。

我试过了:

  

pthread_join(iter, (void**)&returnValue);

  

pthread_join(&iter, (void**)&returnValue);

但得到类似的错误:

error: cannot convert std::vector<long unsigned int>::iterator {aka __gnu_c} long unsigned int*, std::vector<long unsigned int>} to pthread_t {aka long unsigned int} 
pthread_join(iter, (void**)&returnValue); <--

error: invalid conversion from std::vector<long unsigned int>::iterator* {aka __gnu_cxx::__normal_iterator<long unsigned int*, std::vector<long unsigned int> >*} to pthread_t {aka long unsigned int} [-fpermissive]}
pthread_join(&iter, (void**)&returnValue); <--

在这两种情况下,很明显我试图指向非指针转换。 pthread_join需要一个非指针 thread_t,但根据定义,迭代器是一个指针,所以取消引用它是不够的?明确的铸造是解决方案的一部分吗?到目前为止,我没有尝试过任何工作。

1 个答案:

答案 0 :(得分:2)

pthread_join()的第一个参数应为pthread_t。

您的迭代器iter的类型为vector<pthread_t>::iterator。这意味着*iter的类型为pthread_t

所以你必须取消引用它:pthread_join(*iter, (void**)&returnValue);

注意: &*iter因此类型为pthread_t *,而&iter是指向迭代器的类型指针。