ppk*_*ppk 3 c++ linux pthreads
我想创建一个传递vector作为参数的线程.但我得到以下错误:
error: invalid conversion from ‘int’ to ‘void* (*)(void*)’ [-fpermissive] error: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’ [-fpermissive]
我有以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我怎么能做得好呢?谢谢
编辑:忘了包含在这里发布的内容; 修订.
我遇到了新的错误:
error: stray ‘\305’ in program error: stray ‘\231’ in program
我想知道它.
提前致谢.
FINAL EDIT : Thanks to all. Sorry, I had another int var called func in other location. Thanks for your help.
你忘了包括<vector>; 这会使编译器在首次生成失败时感到困惑func,然后无法将其识别为调用中的函数pthread_create.
一旦你包含它,你的代码应该编译(static_cast<void*>如果你愿意,你可以删除它); 但要正常工作,您还需要pthread_join在向量超出范围之前调用,并从中返回值func.
更新:你最新的修改已断码:你应该不会投func给void*,而是把它作为一个函数指针.这应该工作:
pthread_create(&thread, NULL, func, &integers);
Run Code Online (Sandbox Code Playgroud)
错误就像stray ‘\305’ in program暗示你的代码中有一些奇怪的字符,尽管它们不在你发布的代码中.查看错误消息所引用的行.