0

In my header file, I have the following declaration under private:

void *computeSignalBlock(void *);

Now, I fail to compile attempting to pass this method to the pthread_create method. The error is:

cannot convert ‘medianfilter::computeSignalBlock’ from
type ‘void* (medianfilter::)(void*)’ to type ‘void* (*)(void*)’

Why is that looking at my implementations below?

void medianfilter::computeFilteredResults(vector<float> _signals, int _nThreads,
        int _windowSize, bool _isParallel) {

    // Set instance variables.
    originalSignalVector = _signals;
    nThreads = _nThreads;
    windowSize = _windowSize;
    isParallel = _isParallel;

    // Create the threads,
    pthread_t threads[nThreads];
    pthread_attr_t attr;
    // Initialize and set thread joinable
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for (int i = 0; i < nThreads; i++) {
        pthread_create(&threads[i], NULL, computeSignalBlock, (void *) i);
    }

}

void *medianfilter::computeSignalBlock(void *block) {
    //TODO I need  access to instance variables!
}
feder
  • 1,849
  • 2
  • 25
  • 43
  • 1
    Duplicate? http://stackoverflow.com/questions/1815705/i-am-new-to-threads-what-does-this-compile-error-mean/1815784#1815784 – AAT Oct 23 '14 at 09:19

1 Answers1

2

You can't pass member function pointers to pthread_create.

You'll need to declare an appropriate static function in your class (you can pass the this pointer using the void* parameter).

class medianfilter {

    static void* computeSignalBlock(void *);
};

void *medianfilter::computeSignalBlock(void *instance) {    
    medianfilter* thisPtr = reinterpret_cast<medianfilter*>(instance);

    //TODO I need  access to instance variables!
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • But using static, I could no longer use instance variables (or is that different from Java)? – feder Oct 23 '14 at 09:19
  • 1
    @feder See how to do it, I've updated my sample. – πάντα ῥεῖ Oct 23 '14 at 09:21
  • No I get the following error despite having included and added the flag -pthread. undefined reference to `pthread_create'. I added -pthread as a linker flag and now it works. – feder Oct 23 '14 at 09:46
  • @ππάντα ῥεῖ How could rewrite the code to have this method not static. Why I'm asking? every method get's the increment value `i`, to which it should perform only a block of a vector (instance variable). How to do that? – feder Oct 23 '14 at 09:49
  • 2
    @feder: The function has to be static (or a non-member). If you need to give it both a `medianfilter` instance and one or more arguments, then pass a pointer to a struct containing everything it needs. (Or, better still, use the C++11 thread library, unless you've got a good reason for living in the past.) – Mike Seymour Oct 23 '14 at 10:05