Reputation: 5457
Getting the following errors in a function that should take an int k and create k pthreads:
cse451.cpp:95:60: error: invalid conversion from ‘void*’ to ‘pthread_t* {aka long unsigned int*}’ [-fpermissive]
cse451.cpp:97:54: error: invalid use of void expression
I have a feeling it has to do with the foo() function (which at this point is used as nothing more than a placeholder foo(){} )
The relevant code is listed below (line 95 is pthread_t *threads...... and line 97 is err=pthread_create....)
void createThreads(int k){
int numThreads = k;
int i = 0;
int err = 0;
pthread_t *threads = malloc(sizeof(pthread_t) * numThreads);
for(i = 0;i<numThreads;i++){
err = pthread_create(&threads[i], NULL, foo(), NULL);
if(err != 0){
printf("error creating thread\n");
}
}
}
void foo(){}
Upvotes: 1
Views: 2676
Reputation: 1564
There are at least two things wrong:
The prototype for the function should be something like
void *f(void *);
I.e. it should take a pointer to void as an argument, and return a pointer to void.
Your call to pthread_create should look something like this:
void *foo(void*);
err = pthread_create(&threads[i], NULL, foo, NULL);
Upvotes: 3
Reputation: 254421
The first problem is that you're trying to compile C with a C++ compiler. This conversion:
pthread_t *threads = malloc(sizeof(pthread_t) * numThreads);
from an untyped void*
pointer returned by malloc
, to a typed pthread_t*
pointer, is allowed in C but needs a cast in C++.
pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));
But if this is meant to be C++, you'd be better off with
std::vector<pthread_t> threads(numThreads);
so you don't need to juggle the memory yourself. You might also want to look at the standard thread library, which is more friendly than POSIX threads.
The second problem is the argument to pthread_create
should be a function pointer foo
, not the result of calling a function foo()
. You also have the wrong type for the function; it must take and return void*
void *foo(void*);
It's passed the argument you provided to pthread_create
(NULL
in this case), and returns a pointer to anything you want to receive when you join the thread (return NULL;
if you don't want to return anything).
Upvotes: 5
Reputation: 1
cse451.cpp:97:54: error: invalid use of void expression
You need to pass the function pointer of foo()
to pthread_create()
, instead of calling the function
pthread_create(&threads[i], NULL, foo, NULL); // << See the parenthesis are
// omitted
Upvotes: 1