Thrift TThread

Thrift TThread的使用

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <thrift/concurrency/Thread.h>  
  3. #include <thrift/concurrency/PlatformThreadFactory.h>  
  4. #include <boost/shared_ptr.hpp>  
  5.   
  6. using namespace boost;  
  7. using namespace apache::thrift::concurrency;  
  8.   
  9. class MyTask : public Runnable {  
  10.     public:  
  11.         MyTask() {}  
  12.         void run() {  
  13.             std::cout << "\t\t hello world" << std::endl;  
  14.         }     
  15. };  
  16.   
  17. int main() {  
  18.     shared_ptr<MyTask> task(new MyTask());  
  19.       
  20.     PosixThreadFactory threadFactory;  
  21.     threadFactory.setDetached(false);  
  22.   
  23.     shared_ptr<Thread> thread = threadFactory.newThread(task);  
  24.     thread->start();  
  25.     thread->join();  
  26.   
  27.     return 0;  
  28. }  

下面看看Thread的实现, 下面的demo只是写了一个Thread实现的基本思路:

[cpp]  view plain copy
  1. #include <boost/shared_ptr.hpp>  
  2. #include <auto_ptr.h>  
  3. #include <thread>  
  4. #include <iostream>  
  5.   
  6. using namespace boost;  
  7.   
  8. class Runnable {  
  9.     public:  
  10.         virtual ~Runnable() {}  
  11.         virtual void run() = 0;  
  12. };  
  13.   
  14. class Thread {  
  15.     public:  
  16.         static void* threadMain(void *);   
  17.   
  18.     public:  
  19.         Thread(shared_ptr<Runnable> runnable) {  
  20.             runnable_ = runnable;  
  21.         }     
  22.   
  23.         ~Thread() {  
  24.             try {  
  25.                 thread_->join();  
  26.             } catch (...) {  
  27.                 // We're really hosed.  
  28.             }     
  29.         }     
  30.   
  31.         void start() {  
  32.             auto function = std::bind(threadMain, (void *)this);  
  33.             thread_ = std::auto_ptr<std::thread>(new std::thread(function));  
  34.         }     
  35.         void join() {  
  36.             thread_->join();  
  37.         }     
  38.     private:  
  39.         shared_ptr<Runnable> runnable_;  
  40.         std::auto_ptr<std::thread> thread_;  
  41. };  
  42.   
  43. void *Thread::threadMain(void *arg) {  
  44.     Thread *thread = (Thread *)arg;  
  45.     thread->runnable_->run();  
  46.     return (void *)0;  
  47. }  
  48.   
  49. class Task : public Runnable {  
  50.     public:  
  51.         void run() {  
  52.             std::cout << "Task is running..." << std::endl;  
  53.         }     
  54. };  
  55.   
  56. int main() {  
  57.     boost::shared_ptr<Runnable> runnable(new Task());  
  58.     boost::shared_ptr<Thread> thread(new Thread(runnable));  
  59.     thread->start();  
  60.     thread->join();  
  61. }  

上面代码有什么问题呢? 

我们知道我们通常用这样的方式创建一个Thread:

[cpp]  view plain copy
  1. boost::shared_ptr<Thread> thread(new Thread(runnable));  

可是在start函数中:

[cpp]  view plain copy
  1. void start() {  
  2.     auto function = std::bind(threadMain, (void *)this);  
  3.     thread_ = std::auto_ptr<std::thread>(new std::thread(function));  
  4. }   

我们把this传到了threadMain函数中。为了安全起见,我们需要传递一个自身的智能指针,防止double free.

1. 添加自己的指针,避免循环引用,使用week_ptr

[cpp]  view plain copy
  1. class BoostThread  {  
  2.     private:  
  3.         week_ptr<BoostThread> self_;  
[cpp]  view plain copy
  1. public:  
[cpp]  view plain copy
  1. void weakRef(shared_ptr<BoostThread> self) {  
  2. assert(self.get() == this);  
  3. self_ = weak_ptr<BoostThread>(self);  
  4. }  
}

 

2. newThread中,调用完构造函数后,调用weekRef传入自己。

[cpp]  view plain copy
  1. shared_ptr<Thread> newThread(shared_ptr<Runnable> runnable) const {  
  2.   shared_ptr<BoostThread> result = shared_ptr<BoostThread>(new BoostThread(detached_, runnable));  
  3.   result->weakRef(result);  
  4.   runnable->thread(result);  
  5.   return result;  
  6. }  

3. 在start函数中

[cpp]  view plain copy
  1. void start() {  
  2. // Create reference  
  3.   shared_ptr<BoostThread>* selfRef = new shared_ptr<BoostThread>();  
  4.   *selfRef = self_.lock();  
  5.   
  6.   thread_ = std::auto_ptr<boost::thread>(new boost::thread(boost::bind(threadMain, (void*)selfRef)));  
  7. }  
这样selfRef就获得了this实例的控制权,并转移到threadMain函数中

4. threadMain函数

[cpp]  view plain copy
  1. void* BoostThread::threadMain(void* arg) {  
  2.   shared_ptr<BoostThread> thread = *(shared_ptr<BoostThread>*)arg;  
  3.   delete reinterpret_cast<shared_ptr<BoostThread>*>(arg);  
  4.      thread->state_ = started;  
  5.   thread->runnable()->run();  
  6. }  

这个代码示例如下:

[cpp]  view plain copy
  1. #include <boost/shared_ptr.hpp>  
  2. #include <boost/weak_ptr.hpp>  
  3. #include <auto_ptr.h>  
  4. #include <thread>  
  5. #include <iostream>  
  6.   
  7. using namespace boost;  
  8. using boost::shared_ptr;  
  9. using boost::weak_ptr;  
  10.   
  11. class Runnable {  
  12.     public:  
  13.         virtual ~Runnable() {}  
  14.         virtual void run() = 0;  
  15. };  
  16.   
  17. class Thread {  
  18.     private:  
  19.         weak_ptr<Thread> self_;  
  20.         shared_ptr<Runnable> runnable_;  
  21.         std::auto_ptr<std::thread> thread_;  
  22.     public:  
  23.         static void* threadMain(void *);   
  24.   
  25.     public:  
  26.         Thread(shared_ptr<Runnable> runnable) {  
  27.             runnable_ = runnable;  
  28.         }     
  29.   
  30.         ~Thread() {  
  31.             try {  
  32.                 thread_->join();  
  33.             } catch (...) {  
  34.                 // We're really hosed.  
  35.             }     
  36.         }     
  37.   
  38.         void start() {  
  39.             shared_ptr<Thread> *selfRef = new shared_ptr<Thread>();  
  40.             *selfRef = self_.lock();  
  41.             auto function = std::bind(threadMain, (void *)(selfRef));  
  42.             thread_ = std::auto_ptr<std::thread>(new std::thread(function));  
  43.         }     
  44.         void join() {  
  45.             thread_->join();  
  46.         }     
  47.         void weakPtr(shared_ptr<Thread> self) {  
  48.             self_ = self;  
  49.         }     
  50. };  
  51.   
  52. void *Thread::threadMain(void *arg) {  
  53.     shared_ptr<Thread> *p = (shared_ptr<Thread> *)arg;  
  54.     shared_ptr<Thread> thread = *p;   
  55.     delete p;  
  56.   
  57.     thread->runnable_->run();  
  58.     return (void *)0;  
  59. }  
  60. class ThreadFactory {  
  61.     public:  
  62.         static shared_ptr<Thread> newThread(shared_ptr<Runnable> runnable) {  
  63.             shared_ptr<Thread> thread(new Thread(runnable));  
  64.             thread->weakPtr(thread);  
  65.             return thread;  
  66.         }     
  67. };  
  68. class Task : public Runnable {  
  69.     public:  
  70.         void run() {  
  71.             std::cout << "Task is running..." << std::endl;  
  72.         }  
  73. };  
  74.   
  75. int main() {  
  76.     shared_ptr<Runnable> runnable(new Task());  
  77.     shared_ptr<Thread> thread = ThreadFactory::newThread(runnable);  
  78.     thread->start();  
  79.     thread->join();  
  80. }  
下面的代码展示了通过创建Helper(Agent)的方式传递本身的方法:
#include <iostream>
#include <thrift/concurrency/Thread.h>
#include <thrift/concurrency/PlatformThreadFactory.h>
#include <boost/shared_ptr.hpp>                        
#include <boost/make_shared.hpp>

using namespace boost;
using namespace apache::thrift::concurrency;
class ServerThread {                                   
public:
    ServerThread() : helper_(new Helper(this)), running_(false) {
    }       
    void start() {
        assert(!running_);
        running_ = true;                               

        PosixThreadFactory threadFactory;              
        threadFactory.setDetached(false);              
        thread_ = threadFactory.newThread(helper_);    
        thread_->start();

    }   
    void run() {
        std::cout << "serverThread Running..." << std::endl;    
    }   
    void stop() {
        std::cout << "serverThread stopping..." << std::endl;   
        if (running_)
          thread_->join();                             
    }   
    ~ServerThread() {                                  
        if (running_) {
            try {
                stop();
            } catch (...) {
                std::cout << "error shutting down server" << std::endl; 
            }
        }
    }
private:
    class Helper : public Runnable {
    public:
        Helper(ServerThread *serverThread) : serverThread_(serverThread) {
        }
        void run() {
            serverThread_->run();
        }
    private:
        ServerThread *serverThread_;
    };

    bool running_;
    boost::shared_ptr<Helper> helper_;
    boost::shared_ptr<Thread> thread_;
};

int main()
{
    shared_ptr<ServerThread> serverThread = boost::make_shared<ServerThread>();
    serverThread->start();
    return 0;
}


吐槽: CSDN的编辑空间糟透了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值