您的位置:首页 > 其它

Poco::Thread

2012-08-17 17:33 260 查看
Poco实现线程的机制,它将线程Thread和线程运行的实体Runnable分离开来,就像一个框架,Thread管理线程优先级,堆栈,维护线程局部变量;而运行的代码是在Runnable的子类run方法中实现的。



我们在MyRunnable中,重写run方法,实现线程逻辑代码,然后调用Thread中的start方法启动线程,用join回收线程资源。静态方法sleep用于延时挺有用的。如果我们想将一个静态方法或全局函数用做线程的代码,可以使用ThreadTarget对那个函数进行包装;类中的非静态方法可以使用RunnableAdapter进行包装,然后用Thread进行调用。

demo

#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/ThreadTarget.h"
#include "Poco/RunnableAdapter.h"

using Poco::Thread;
using Poco::Runnable;
using Poco::ThreadTarget;
using Poco::RunnableAdapter;

class MyRunnable:public Runnable
{
public:
    void run() { std::cout << "hello MyRunnable." << std::endl; }
};

void gFun4Td()
{
    std::cout << "hello gFun4Td" << std::endl;
}

class staticFun4Td
{
public:
    static void staticFun() { std::cout << "hello static fun." << std::endl; }
};

class commFun4Td
{
public:
    void commFun() { std::cout << "hello common function." << std::endl; }
};

int main()
{
    Thread t1("MyRun");
    Thread t2("global");
    Thread t3("static");
    Thread t4("comm");

    MyRunnable rMy;
    ThreadTarget rg(gFun4Td);
    ThreadTarget rs(&staticFun4Td::staticFun);
    commFun4Td com;
    RunnableAdapter<commFun4Td> rc(com,&commFun4Td::commFun);

    t1.start(rMy);
    Thread::sleep(100);
    t2.start(rg);
    Thread::sleep(100);
    t3.start(rs);
    Thread::sleep(100);
    t4.start(rc);

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: