线程

一个线程表示一块可以运行的代码,因此 wvl::thread 提供了可操作的接口。

wvl::thread 可以给一个成员函数、全局普通函数和函数对象启动一个线程,而这些函数和函数对象都不能带有参数。例如:

void function()
{
   wvl::message_box.show("Hello, world");
}

class functor
{
public:
    void operator()() const
    {
         wvl::message_box.show("Hello, world");
    }
};

所有的线程对象在刚创建时都不是活动的,调用 thread::start才能开辟一个线程。当一个线程执行完毕,它将自动清理并释放资源。

int WINAPI WinMain (HINSTANCE hThisInstance,HINSTANCE, char*, int)
{
    wvl::thread thread_;

    thread_.start(&function);  //don't forget operator &!
    thread_.wait();

    thread_.start(functor());
    thread_.wait();
    return 0;
}

用线程的另一个方法是创建一个类,定义一个 wvl::thread 数据成员。例如

class foo
{
public:
    foo(){}

    ~foo(){   thread_.wait();  }

    void thread_demo(){
        thread_.start(this, &foo::sample);
    }

private:
    void sample() {
        wvl::message_box.show("Hello, world");
    }
private:
    wvl::thread thread_; 
};

int WINAPI WinMain (HINSTANCE hThisInstance,HINSTANCE, char*, int)
{
    foo x;
    x.thread_demo();
    return 0;
}

当一个线程还存在的时候,
- thread::paused () 表示线程是否暂停了。
- thread::pause () 暂停一个线程,并用
- thread::resume () 开启暂停的线程。
- thread::wait () 阻塞等该线程的结束。  
- thread::empty () 表示当前线程是否还存在。
- thread::handle() 返回线程的句柄,该句柄可以由系统自身的API操作。

wvl::thread 可以拷贝构造和复制,但是这对它没有用,如果发生这种操作将没有任何作用。

Return to Index