如何通过vector< int>在C ++中正确pthread_create? [英] How pass vector<int> to pthread_create correctly in C++?
问题描述
我想创建一个将向量作为参数传递的线程. 但是我遇到了以下错误:
I would like to create a thread passing a vector as parameter. but i got the following errors:
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;
}
我该怎么做呢? 谢谢
仅在此处忘记了包含的帖子;已修改.
forgot the includes posting here only; Revised.
我遇到了新的错误:
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
时无法将其标识为函数.
You have forgotten to include <vector>
; this confuses the compiler as it first fails to generate func
, and then fails to identify it as a function in the call to pthread_create
.
添加了该代码后,您的代码应进行编译(并且您可以根据需要删除static_cast<void*>
);但是要正常工作,您还需要在向量超出范围之前调用pthread_join
,并从func
返回值.
Once you include that, your code should compile (and you can remove the static_cast<void*>
if you like); but to work correctly you also need to call pthread_join
before the vector goes out of scope, and return a value from func
.
更新:您的最新编辑已破坏了代码:您应该不将func
强制转换为void*
,但应将其保留为函数指针.这应该起作用:
UPDATE: your latest edit has broken the code: you should not cast func
to void*
, but leave it as a function pointer. This should work:
pthread_create(&thread, NULL, func, &integers);
类似stray ‘\305’ in program
的错误意味着您的代码中包含一些奇怪的字符,尽管它们不在您发布的代码中.看一下错误消息所指的行.
Errors like stray ‘\305’ in program
imply that you have some strange characters in your code, although they're not in the code you've posted. Have a look at the lines that the error messages refer to.
这篇关于如何通过vector< int>在C ++中正确pthread_create?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!