c ++ - 将向量传递给线程

时间:2017-11-27 06:38:05

标签: c++ c++11

如下所示,我通过pthread_create传递矢量时收到如下错误。

#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;

void foo(void *a)
{
  vector <int> b = (vector <int>*)a;

  for(int i=0; i<b.size(); i++)
  {
        std::cout<<b[i];
  }
  return NULL;
}

void bar(int x)
{
  std::cout<<"bar";
}

int main()
{
  pthread_t thr;
  std::vector <int> a = {1,2,3};
  pthread_create(&thr, NULL, &foo, (void *)&a);
  pthread_join(thr,NULL);
  return 0;

错误讯息:

threadeg.cpp: In function ‘void foo(void*)’:
threadeg.cpp:9:35: error: conversion from ‘std::vector<int>*’ to non-scalar type ‘std::vector<int>’ requested
   vector <int> b = (vector <int>*)a;

threadeg.cpp:16:10: error: return-statement with a value, in function returning 'void' [-fpermissive]
   return NULL;
          ^
threadeg.cpp: In function ‘int main()’:
threadeg.cpp:28:46: error: invalid conversion from ‘void (*)(void*)’ to ‘void* (*)(void*)’ [-fpermissive]
   pthread_create(&thr, NULL, &foo, (void *)&a);

/usr/include/pthread.h:244:12: error:   initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’ [-fpermissive]
 extern int pthread_create (pthread_t *__restrict __newthread,

我是线程的新手,我无法弄清楚出了什么问题。任何人都可以指出问题并提出解决方案吗?

3 个答案:

答案 0 :(得分:2)

首先,你有一些错误,即void函数不会返回任何内容。在您的情况下,它返回NULL。根据定义,NULL只不过是零。因此,返回NULL并不意味着不返回任何内容。

bar()功能是不必要的。

现在检查工作代码。

#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;

void *foo(void *a)
{
   vector <int>* b = (vector <int>*)a;

   for (auto it : *b) {
   std::cout << it;
   }
}

int main()
{
  pthread_t thr;
  std::vector <int> a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  pthread_create(&thr, NULL, &foo, &a);
  pthread_join(thr,NULL);
  return 0;
}

你要发送你的矢量地址。而且你还有一个void *返回函数,而不是void返回函数。你也可以发送它的地址。

答案 1 :(得分:1)

我认为你想要创建一个指针b而不是一个副本vector <int>* b = (vector <int>*)a;,几乎没有什么错误。 函数foo签名应该是void* foo (void* a)而不是void foo(void* a)

答案 2 :(得分:1)

您应该将a转换为vector <int>* b或引用如下所示,因为您传递指针并尝试将其指定给对象。

foo的回复更改为(void*),因为pthread_create需要void *(*start_routine) (void *)

#include <iostream>
#include <pthread.h>
#include <vector>

using namespace std;

void* foo(void *a)
{
  const vector <int>& b = *(vector <int>*)a; // Cast to a reference or pointer, could be made const

  for(int i=0; i<b.size(); i++)
  {
        std::cout<<b[i];
   }
    return NULL;
}

void bar(int x)
{
  std::cout<<"bar";
}

int main()
{
  pthread_t thr;
  std::vector <int> a = {1,2,3};
  pthread_create(&thr, NULL, &foo, (void *)&a);
  pthread_join(thr,NULL);
  return 0;
}

您可以在此处https://ideone.com/S1bWSk尝试。

<强>更新 是的,如果可以切换到std::thread会更好。您可以通过引用传递数组。

void foo(const vector <int>& b)
{
   for(int i=0; i<b.size(); i++)
   {
        std::cout<<b[i];
   }
}

....

std::thread thr(foo, std::cref(a));
thr.join();