Thread类封装

class CThread : public CObject
{
 public:
   CThread();
   
   virtual ~CThread();
   
   void start();
   
   void join();

   void detach();

   pthread_t getThreadId() const
   {
    return m_threadId;
   }
   
 private:
   virtual void run() = 0;
 
   void createThread();
 protected:

   CThread(const CThread& other);
   
   CThread& operator = (const CThread& other);

   friend void * threadFunc (void * voidPointer);
   
   pthread_t m_threadId;
 
};

 

 CThread::CThread() :m_threadId (0)
{
 ;
}

CThread::~CThread()
{
 ;
}

void * threadFunc (void * voidPointer)
{
 if (voidPointer == NULL)
 {
  throw CException ("threadFunc() : Paramater pass to thread is NULL");
 }

 CThread * thread = static_cast <CThread *> (voidPointer);
 thread->run ();

 return NULL;
}

void CThread::createThread ()
{
 if (0 != pthread_create (&this->m_threadId, NULL, threadFunc, this))
 {
  throw CException("CThread::createThread fail");
 }
}

void CThread::start ()
{
 this->createThread ();
}

void CThread::join()
{
 if (0 != pthread_join (this->m_threadId, NULL))
 {
  throw CException("CThread::join fail ");
 }
}

void CThread::run()
{
 ;
}

void CThread::detach()
{
 if (0 != pthread_detach(this->m_threadId))
 {
  throw CException("CThread::detach fail ");
 }
}

### 创建自定义线程的方法 在 Python 的 `threading` 模块中,可以通过继承 `Thread` 来创建自定义线程。这种方式允许开发者通过重写特定方法来自定义线程的行为。以下是具体实现的方式: #### 继承 Thread 当需要扩展 `Thread` 的功能时,通常会创建一个新的子并覆盖其 `run()` 方法。这是因为在启动线程时(即调用 `start()` 方法),内部机制会自动调用该线程实例的 `run()` 方法。 ```python import threading class MyCustomThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 调用父构造器[^1] def run(self): while True: print(f"{threading.current_thread().name} is running") # 获取当前线程名称[^2] break # 示例退出循环条件 ``` 上述代码展示了如何创建一个名为 `MyCustomThread` 的自定义线程。它实现了两个主要部分: - 构造函数 (`__init__`):用于初始化线程属性,并确保调用了父的构造函数。 - 自定义行为 (`run`):定义了线程执行的具体逻辑。 #### 使用自定义线程 一旦定义好自定义线程,就可以像普通线程一样使用它们。下面是一个简单的例子展示如何启动多个自定义线程: ```python if __name__ == "__main__": threads = [] for _ in range(3): # 启动三个线程 thread_instance = MyCustomThread() threads.append(thread_instance) thread_instance.start() for t in threads: # 等待所有线程完成 t.join() ``` 这段代码片段说明了如何批量创建和管理多条线程。注意,在实际应用中可能还需要考虑资源竞争等问题,这可通过锁或其他同步工具解决。 #### 守护线程设置 如果希望某些线程作为后台进程存在而不影响主程序结束,则可以在初始化阶段将其设为守护线程: ```python def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.daemon = True # 将线程标记为守护状态[^3] ``` 这样做的好处在于即使这些线程尚未完全终止,只要主线程结束了整个应用程序也会随之关闭。 --- ### 总结 通过继承 `threading.Thread` 并重新定义其中的关键组件如 `__init__` 和 `run` 方法,能够灵活构建满足需求的各种复杂场景下的并发处理方案。同时合理配置诸如守护模式这样的附加选项有助于优化整体性能表现以及异常情况下的健壮性保障。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值