21xrx.com
2024-09-19 23:55:22 Thursday
登录
文章检索 我的文章 写文章
C++11 线程的封装实现
2023-06-29 14:56:03 深夜i     --     --
C++ C++11 线程 封装 实现

C++11 引入了对多线程的支持,其中最重要的特性就是 std::thread 类的出现。它是一个轻量级的线程类,可以用来创建一个新的线程。不过,使用 std::thread 类还是有一些不便之处,比如线程的启动、加入、分离等操作都需要手动进行,容易出错,可维护性较差。因此,对 std::thread 进行封装已经成为了大多数 C++ 多线程程序员的常见需求。

下面介绍一种基于 C++11 标准库的线程库,它提供了一个简单易用的接口,对 std::thread 进行了封装。以下是它的主要特点:

1. 使用 std::function 类型作为线程函数参数类型,方便传递函数对象。这样就不需要使用函数指针或类成员函数指针等方式来传递函数了。

2. 提供类似 RAII(资源获取即初始化)的机制。线程对象生命周期结束时自动调用 join() 或 detach(),避免了手工调用这些函数的麻烦和可能的错误。

3. 支持线程的取消功能。在执行一些长时间任务时,可以通过调用 thread::interrupt() 函数取消线程。

以下是代码示例:


#include <thread>

#include <functional>

#include <stdexcept>

class Thread{

public:

Thread(){}

~Thread(){

try{

if(m_thread.joinable()){m_thread.join();}

}catch(const std::exception& e){std::cerr << e.what() << '\n';}

}

Thread(Thread&& other){

*this = std::move(other);

}

Thread& operator=(Thread&& other){

if(this != &other){

try{

if(m_thread.joinable()){m_thread.join();}

}catch(const std::exception& e){std::cerr << e.what() << '\n';}

m_thread = std::move(other.m_thread);

m_isInterrupted = std::move(other.m_isInterrupted);

other.m_isInterrupted = false;

}

return *this;

}

template<typename Function, typename... Args>

explicit Thread(Function&& f, Args&&... args): m_thread(std::forward<Function>(f), std::forward<Args>(args)...), m_isInterrupted(false){}

template<typename Function, typename... Args>

void interruptible(Function&& f, Args&&... args){

try{

std::thread t(f, std::forward<Args>(args)...);

m_thread = std::move(t);

m_isInterrupted = false;

}catch(const std::exception& e){std::cerr << e.what() << '\n';}

}

bool interrupt() noexcept{

m_isInterrupted = true;

return m_thread.joinable();

}

void join(){

if(!m_thread.joinable()){throw std::logic_error("thread is not joinable");}

m_thread.join();

}

void detach(){

if(!m_thread.joinable()){throw std::logic_error("thread is not joinable");}

m_thread.detach();

}

bool is_interrupted() const noexcept

return m_isInterrupted;

bool joinable() const noexcept{

return m_thread.joinable();

}

std::thread::id get_id() const noexcept{

return m_thread.get_id();

}

void swap(Thread& other) noexcept{

m_thread.swap(other.m_thread);

std::swap(m_isInterrupted, other.m_isInterrupted);

}

private:

std::thread m_thread;

bool m_isInterrupted;

};

以上就是一个简单的 C++11 线程库的封装实现。这个库只是一个基础版,如果想要更多的功能,例如线程池、移动语义改进等,可以在此基础上扩展。这里的示例代码仅供参考,如果您有更好的方式来封装 std::thread,欢迎留言分享。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复