使用C++11线程基类

Thread base class using C++11

本文关键字:基类 线程 C++11 使用      更新时间:2023-10-16

由于我是C++11的新手,我正在寻找一个使用C++11多线程功能的线程基类的正确实现,该功能将参数传递给类,启动和停止线程。所以像这样的事情:http://www.codeproject.com/Articles/21114/Creating-a-C-Thread-Class但是使用C++11来获得操作系统独立性。

我在谷歌上搜索过,但没有发现任何有用的东西。也许有人熟悉一个好的开源实现?

编辑为了准确地解释我的问题:我已经知道std::thread,但我的意图和目标分别是为std::thread使用一个包装器类,以避免大量处理它。我现在使用下面的类结构(从1年开始)。但我被分别绑定到Windows API,这不是我想要的。

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;
};

查看std::thread

#include <iostream>
#include <thread>
void function()
{
    std::cout << "In Threadn";
}
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();
}

您需要的所有线程支持都可以在这里找到。