4
votes

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]

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.
1
the error is about the 3rd argument, not about the 4th; are you pasting the exact code for reproducing the error? because the compiler doesn't seem to know what 'func' is, so it treats it as an intstijn
As for the casting... You don't need to cast the vector in the call to pthread_create, but in the thread function you must use reinterpret_cast instead.Some programmer dude
@stijn Yes, it's the exact code, I am going to cast func. I don`t know why does not recognize the callback.ppk
@ppk: Are you sure you get those errors from that code? Now you've added #include <vector>, GCC compiles it with only a warning, due to missing a return in func. What is your compiler, and are they the only compile errors?Mike Seymour
@MikeSeymour Yes, the includes are right; I am using g++ with codelite under ubuntu 11.10.ppk

1 Answers

6
votes

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.

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.

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);

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.