我们先简单的用pthread来实现一个简单的线程类,采用function的方式来,执行用户需要在线程里面执行的函数。 function相对于指针函数来说,功能更强大
//线程类的定义 //pthread相关api //pthread_create, pthread_detach, pthread_join class Thread { public: typedef std::shared_ptr<Thread> ptr; Thread(std::function<void()> cb, const std::string& name); ~Thread(); pid_t getId() const { return m_id;} const std::string& getName() const { return m_name;} void join(); static Thread* GetThis(); static const std::string& GetName(); static void SetName(const std::string& name); private: Thread(const Thread&) = delete; Thread(const Thread&&) = delete; Thread& operator=(const Thread&) = delete; static void* run(void* arg); private: pid_t m_id = -1; pthread_t m_thread = 0; std::function<void()> m_cb; std::string m_name; Semaphore m_semaphore; };信号量(Semaphore)多用于生产消费者模式,消息队里。一个线程负责接收请求,把请求发送到消息队列,并且把信号+1,其他线程在wait信号,信号大于0时,执行相应行为,否则就阻塞等待
//相关函数 //sem_init, sem_destroy, sem_wait, sem_post class Semaphore { public: Semaphore(uint32_t count = 0); ~Semaphore(); void wait(); void notify(); private: Semaphore(const Semaphore&) = delete; Semaphore(const Semaphore&&) = delete; Semaphore& operator=(const Semaphore&) = delete; private: sem_t m_semaphore; };用户多线程操作数据时,做保护,保证同一时间,只有一种操作。保证数据行为不出错。 互斥量有多种类型,Mutex,RWMutex,Spinlock 都可以算的上是这一类。保证多线程操作数据的安全
//互斥量 class Mutex { public: typedef ScopedLockImpl<Mutex> Lock; Mutex() { pthread_mutex_init(&m_mutex, nullptr); } ~Mutex() { pthread_mutex_destroy(&m_mutex); } void lock() { pthread_mutex_lock(&m_mutex); } void unlock() { pthread_mutex_unlock(&m_mutex); } private: pthread_mutex_t m_mutex; }; //读写互斥量 class RWMutex { public: typedef ReadScopedLockImpl<RWMutex> ReadLock; typedef WriteScopedLockImpl<RWMutex> WriteLock; RWMutex() { pthread_rwlock_init(&m_lock, nullptr); } ~RWMutex() { pthread_rwlock_destroy(&m_lock); } void rdlock() { pthread_rwlock_rdlock(&m_lock); } void wrlock() { pthread_rwlock_wrlock(&m_lock); } void unlock() { pthread_rwlock_unlock(&m_lock); } private: pthread_rwlock_t m_lock; }; //spinlock class Spinlock { public: typedef ScopedLockImpl<Spinlock> Lock; Spinlock() { pthread_spin_init(&m_mutex, 0); } ~Spinlock() { pthread_spin_destroy(&m_mutex); } void lock() { pthread_spin_lock(&m_mutex); } void unlock() { pthread_spin_unlock(&m_mutex); } private: pthread_spinlock_t m_mutex; };github: https://github.com/sylar-yin/sylar 视频地址: https://www.bilibili.com/video/av53129011/ 个人主页:http://www.sylar.top/