简体   繁体   English

如何在C ++中正确地将vector <int>传递给pthread_create?

[英]How pass vector<int> to pthread_create correctly in C++?

I would like to create a thread passing a vector as parameter. 我想创建一个传递vector作为参数的线程。 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]

I have the following code: 我有以下代码:

#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;
}

How I can do it properly ? 我怎么能做得好呢? Thanks 谢谢

EDIT: forgot the includes posting here only; 编辑:忘了包含在这里发布的内容; Revised. 修订。

I got new errors: 我遇到了新的错误:

error: stray ‘\305’ in program
error: stray ‘\231’ in program

I am trying to know about it. 我想知道它。

Thanks in advance. 提前致谢。

FINAL EDIT : Thanks to all. Sorry, I had another int var called func in other location.
Thanks for your help.

You have forgotten to include <vector> ; 你忘了包含<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 . 这会混淆编译器,因为它首先无法生成func ,然后无法在调用pthread_create将其识别为函数。

Once you include that, your code should compile (and you can remove the static_cast<void*> if you like); 一旦你包含它,你的代码应该编译(如果你愿意,你可以删除static_cast<void*> ); but to work correctly you also need to call pthread_join before the vector goes out of scope, and return a value from func . 但要正常工作,您还需要在向量超出范围之前调用pthread_join ,并从func返回一个值。

UPDATE: your latest edit has broken the code: you should not cast func to void* , but leave it as a function pointer. 更新:你最新的修改已断码:你应该投funcvoid* ,而是把它作为一个函数指针。 This should work: 这应该工作:

pthread_create(&thread, NULL, func, &integers);

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. 程序中stray '\\305' in program类的错误意味着您的代码中有一些奇怪的字符,尽管它们不在您发布的代码中。 Have a look at the lines that the error messages refer to. 查看错误消息所引用的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM