【发布时间】:2012-01-23 12:30:41
【问题描述】:
我想创建一个将向量作为参数传递的线程。 但我收到以下错误:
错误:从“int”到“void* (*)(void*)”的无效转换 [-fpermissive] 错误:初始化“int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)” [-fpermissive] 的参数 3我有以下代码:
#include <iostream>
#include <vector>
#include <pthread.h>
using namespace std;
void* func(void* args)
{
vector<int>* v = static_cast<vector<int>*>(args);
cout << "Vector size: " << v->size();
}
int main ( int argc, char* argv[] )
{
vector<int> integers;
pthread_t thread;
for ( int i = 0; i < 10; i++)
integers.push_back(i+1);
// overheat call
//pthread_create( &thread, NULL, func, static_cast<void*>(&integers));
pthread_create( &thread, NULL,func,&integers);
cout << "Main thread finalized" << endl;
return 0;
}
我怎样才能正确地做到这一点? 谢谢
编辑:忘记了仅在此处发布的包含;已修改。
我遇到了新错误:
错误:程序中出现杂散“\305” 错误:程序中出现杂散“\231”我正在努力了解它。
提前致谢。
最后编辑:谢谢大家。抱歉,我在其他位置有另一个名为 func 的 int var。 谢谢你的帮助。【问题讨论】:
-
错误是关于第三个参数,而不是关于第四个;您是否粘贴了重现错误的确切代码?因为编译器似乎不知道'func'是什么,所以它把它当作一个int
-
至于转换...你不需要在调用
pthread_create时转换向量,但是在线程函数中你必须使用reinterpret_cast。 -
@stijn 是的,这是确切的代码,我要转换 func。不知道为什么不识别回调。
-
@ppk:你确定你从那个代码中得到了这些错误吗?现在你已经添加了
#include <vector>,GCC compiles it,但只有一个警告,因为在func中缺少return。你的编译器是什么,它们是唯一的编译错误吗? -
@MikeSeymour 是的,包含是正确的;我在 ubuntu 11.10 下使用 g++ 和 codelite。