C++ erroring creating n pthreads-

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(){}

-------------Problems Reply------------

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

There are at least two things wrong:

  • You need to pass a pointer to a function for the third argument to pthread_create, not the result of a call to the function you intend to run in the thread.
  • 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);

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

Category:c# Views:0 Time:2015-03-13

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.175 (s). 11 q(s)