pthread class implemented in C++ inheritance

I am sharing a set of code generating a thread with pthread by taking an advantage of C++ class inheritance.

You can download the code in this link.

Now, the creation of thread in c++ is easier than before with the standard “thread” class. But still “pthread” is more generic and available in various environments. For my case, I need to control the priority of a thread for real-time applications. In this case, pthread is a good selection.

The creation of pthread in a class environment is very common but it needs some careful implementation because it needs a static function. Hence, the inheritance of C++ can simplify the implementation. We can use a base class including the fundamental functions of pthread, and an application class which needs thread can be created by inheriting the base class.

Simply, You can create your application class using thread like below:

#include <iostream>
#include <unistd.h> // for sleep function

#include "basethreadclass.h"

class MyAppThread: public BaseThreadClass{
    void InternalThreadEntry(){
        int i=0;
        while(1){
            std::cout << i++ << " hello from pthread\n";
            usleep(10000);
        }
    };
};

int main(){
    MyAppThread a;
    a.StartInternalThread();
    int i=0;
    while(1){
        std::cout << i++ << " hello from main\n";
        usleep(10000);
    }
    return 0;
}

The base class, “BaseThreadClass” looks like below:

#ifndef BASETHREADCLASS_H
#define BASETHREADCLASS_H

class BaseThreadClass
{
public:
    BaseThreadClass() {/* empty */}
    virtual ~BaseThreadClass() {/* empty */}

    /** Returns true if the thread was successfully started, false if there was an error starting the thread */
    bool StartInternalThread()
    {
        return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
    }

    /** Will not return until the internal thread has exited. */
    void WaitForInternalThreadToExit()
    {
        (void) pthread_join(_thread, NULL);
    }

protected:
    /** Implement this method in your subclass with the code you want your thread to run. */
    virtual void InternalThreadEntry() = 0;

private:
    static void * InternalThreadEntryFunc(void * This) {((BaseThreadClass *)This)->InternalThreadEntry(); return NULL;}
    pthread_t _thread;
};


#endif // BASETHREADCLASS_H

You can compile them with the included cmake file, and execute the application like below:

crop_thead

I hope this post help your project and understanding. Good luck!

Again you can download the codes link.

 

Reference

[1] https://stackoverflow.com/questions/1151582/pthread-function-from-a-class

 

1 thought on “pthread class implemented in C++ inheritance

Leave a Reply