Search code examples
c++multithreadingclassc++11abstraction

Thread base class using C++11


Since I am new to C++11 I am looking for a proper implemtnation of a thread base class using the C++11 multithreaded features with passing arguments to the class, starting and stoping the thread... . So something like this one: http://www.codeproject.com/Articles/21114/Creating-a-C-Thread-Class but with C++11 to gain OS-independence.

I've googled for it but haven't found anything useful. Perhaps someone is familiar with a good open-source implementation?

EDIT To explain my question precisely: I am already aware of std::thread, but my intention respectively goal is to use a wrapper-class for std::thread to not deal with it heavily. I'm currently using the class-structure below (since 1-year). But I'm stucked respectively bounded to the Windows-APIs which is not what I want.

class ThreadBase {
public:
    ThreadBase();
    virtual ~ThreadBase();

    // this is the thread run function, the "concrete" threads implement this method
    virtual int Run() = 0;

    // controlling thread behaviour, Stop(), Resume()  is not that necessary (I implemented it, beacuse the API gives me the opportunity)
    virtual void Start() const;
    virtual void Stop() const;

    // returns a duplicated handle of the thread
    virtual GetDuplicateHdl() const; //does std::thread give me something similar to that?

protected:
        // return the internal thread handle for derived classes only
    virtual GetThreadHdl() const;
    //...block copy constructor and assignment operator

private:
        // the thread function
    void ThreadFunc(void * Param); //for Windows the return value is WINAPI
    //THandleType? ThreadHdl;
    unsigned long ThreadId;
};

Solution

  • Look at std::thread

    #include <iostream>
    #include <thread>
    
    void function()
    {
        std::cout << "In Thread\n";
    }
    
    int main()
    {
        std::thread x(function);
        // You can not let the object x be destroyed
        // until the thread of execution has finished.
        // So best to join the thread here.
        x.join();
    }
    

    All the threading support you need can be found here.