简体   繁体   中英

How to run a thread inside an object using pthread

I'm having some trouble using this code.

void BV4618::InitializeThreads(void){
    pthread_t T_FIFO, T_Buffer;
    pthread_create( &T_FIFO, NULL, FIFO, NULL);
    pthread_create( &T_Buffer, NULL, readKBuffer, NULL);
}

The methods FIFO and readKBuffer do these things..

void *BV4618::FIFO(void*){
    while (isWorking){
        if (qsize > 0){
            if(params[0] == -1){
                ReceiveData();
            }else{
                SendData(params[0]);
            }
            //printf("Processing in position %d value %d\n", qsize, params[0]);
            ShifterQ();
        }else{
            usleep(50000);
        }
    }
    return NULL;
}

The point is, in a procedural way everything has worked fine without problem. Now, that i'm gonna rewriting everything using classes, i'm encountering some problems like

cannot convert 'BV4618::FIFO' from type 'void* (BV4618::)(void*)' to type 'void* (*)(void*)'    BV4618.cpp

The constructor calls a method named "InitializeThreads" that launches the threads which continuosly are listening for something on that kind of object. What's the solution for the above problem?

I'm not a pthread expert, but the problem is that you try to give a pointer to a member function when the definition of pthread_create() is expecting a function:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                    void *(*start_routine) (void *), void *arg);

pthread will then call a normal "standalone" function giving it arg as argument.

A member function however does not work like a "standalone" function. It is meaningless without without its class and the data that goes along with it.

I'd recommend to create a static wrapper function, and use this (pointer to the class) as argument. The wrapped would then recast the argument as being a BV4618 and call invoque the member function of the class.

The wrapper is a static member function . Static member means that it's independent of the class data:

static void* BV4618::my_wrapper (void* arg) {
    ((BV4618*)arg)->FIFO( );
}

Please note, that in real life, when using separate class declaration (in a header) and definition (code implementation), the static keywork must be provided in the declaration only .

For this to work, you need to redfine slightly your FIFO function, as it will no longer expect an argument:

void *BV4618::FIFO(){
    ...
}

Your init code would then look like:

...
pthread_create( &T_FIFO, NULL, my_wrapper, this);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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