Poco::Thread 【转】

原文:http://www.myexception.cn/program/681578.html

Poco::Thread

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"

#include <iostream>

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

 


posted @ 2013-02-20 13:07  Leo Forest  阅读(1156)  评论(1编辑  收藏  举报