一个线程头文件

来源:互联网 发布:不用网络的导航 编辑:程序博客网 时间:2024/05/21 19:27
#include <stdio.h>#include <stdlib.h>#include <set>#include <pthread.h>namespace mySock {class MutexLock {public:  MutexLock() {    pthread_mutex_init(&mutex_, NULL);  }  ~MutexLock() {    pthread_mutex_destroy(&mutex_);  }  pthread_mutex_t* getMutex() {    return &mutex_;  }  void lock() {    pthread_mutex_lock(&mutex_);  }  void unlock() {    pthread_mutex_unlock(&mutex_);  }private:  pthread_mutex_t mutex_;};class MutexLockGuard {public:  explicit MutexLockGuard(MutexLock &mutex) :      mutex_(mutex) {    mutex_.lock();  }  ~MutexLockGuard() {    mutex_.unlock();  }private:  MutexLock &mutex_;};class Condition{public:  explicit Condition(MutexLock &mutex) :      mutex_(mutex) {    pthread_cond_init(&cond_, NULL);  }  ~Condition() {    pthread_cond_destroy(&cond_);  }  void notify() {    pthread_cond_signal(&cond_);  }  void notifyall() {    pthread_cond_broadcast(&cond_);  }  void wait() {    pthread_cond_wait(&cond_, mutex_.getMutex());  }private:  MutexLock &mutex_;  pthread_cond_t cond_;};class ThreadPool {public:  typedef void* (*threadFunc)(void*);public:  void CreateThread(threadFunc tf, void* arg) {    pthread_t threadId;    if (pthread_create(&threadId, NULL, tf, arg) != 0) {      printf("CreateThread error\n");      exit(-1);    }    threads_.insert(threadId);  }  void joinAll() {    for (auto i: threads_) {      pthread_join(i, NULL);    }  }private:  std::set<pthread_t> threads_;};}


排版有点问题...


说明放在下面,


包含互斥锁、条件变量、线程池的简单封装,改天写一个 生产者-消费者 队列,示范使用方法。