学点 C++11 并发编程

字节流动

共 376字,需浏览 1分钟

 ·

2022-06-11 22:20


c++11关于并发引入了好多好东西,这里按照如下顺序介绍:

  • std::thread 相关

  • std::mutex 相关

  • std::lock 相关

  • std::atomic 相关

  • std::call_once 相关

  • volatile 相关

  • std::condition_variable 相关

  • std::future 相关

  • async 相关



1
std::thread 相关

c++11之前你可能使用 pthread_xxx 来创建线程,繁琐且不易读,c++11 引入了 std::thread 来创建线程,支持对线程 join 或者 detach 。直接看代码:


#include 
#include 

using namespace std;

int main() {
   auto func = []() {
       for (int i = 0; i < 10; ++i) {
           cout << i << " ";
      }
       cout << endl;
  };
   std::thread t(func);
   if (t.joinable()) {
       t.detach();
  }
   auto func1 = [](int k) {
       for (int i = 0; i < k; ++i) {
           cout << i << " ";
      }
       cout << endl;
  };
   std::thread tt(func1, 20);
   if (tt.joinable()) { // 检查线程可否被join
       tt.join();
  }
   return 0;
}


上述代码中,函数 func 和 func1 运行在线程对象 t 和 tt 中,从刚创建对象开始就会新建一个线程用于执行函数,调用 join 函数将会阻塞主线程,直到线程函数执行结束,线程函数的返回值将会被忽略。


如果不希望线程被阻塞执行,可以调用线程对象的detach函数,表示将线程和线程对象分离。


如果没有调用 join 或者 detach 函数,假如线程函数执行时间较长,此时线程对象的生命周期结束调用析构函数清理资源,这时可能会发生错误。


这里有两种解决办法,一个是调用join(),保证线程函数的生命周期和线程对象的生命周期相同,另一个是调用detach(),将线程和线程对象分离。


这里需要注意,如果线程已经和对象分离,那我们就再也无法控制线程什么时候结束了,不能再通过join来等待线程执行完。


这里可以对thread进行封装,避免没有调用join或者detach可导致程序出错的情况出现:


class ThreadGuard {
  public:
   enum class DesAction { join, detach };

   ThreadGuard(std::thread&& t, DesAction a) : t_(std::move(t)), action_(a){};

   ~ThreadGuard() {
       if (t_.joinable()) {
           if (action_ == DesAction::join) {
               t_.join();
          } else {
               t_.detach();
          }
  }
  }

   ThreadGuard(ThreadGuard&&) = default;
   ThreadGuard& operator=(ThreadGuard&&) = default;

   std::thread& get() return t_; }

  private:
   std::thread t_;
   DesAction action_;
};

int main() {
   ThreadGuard t(std::thread([]() {
       for (int i = 0; i < 10; ++i) {
           std::cout << "thread guard " << i << " ";
      }
       std::cout << std::endl;}), ThreadGuard::DesAction::join);
   return 0;
}


c++11还提供了获取线程id,或者系统cpu个数,获取thread native_handle,使得线程休眠等功能。


std::thread t(func);
cout << "当前线程ID " << t.get_id() << endl;
cout << "当前cpu个数 " << std::thread::hardware_concurrency() << endl;
auto handle = t.native_handle();// handle可用于pthread相关操作
std::this_thread::sleep_for(std::chrono::seconds(1));




2
std::mutex 相关

std::mutex 是一种线程同步的手段,用于保存多线程同时操作的共享数据。

mutex 分为四种:


  • std::mutex:独占的互斥量,不能递归使用,不带超时功能;

  • std::recursive_mutex:递归互斥量,可重入,不带超时功能;

  • std::timed_mutex:带超时的互斥量,不能递归;

  • std::recursive_timed_mutex:带超时的互斥量,可以递归使。

拿一个 std::mutex 和 std::timed_mutex 举例吧,别的都是类似的使用方式:

std::mutex:


#include 
#include 
#include 

using namespace std;
std::mutex mutex_;

int main() {
   auto func1 = [](int k) {
       mutex_.lock();
       for (int i = 0; i < k; ++i) {
           cout << i << " ";
      }
       cout << endl;
       mutex_.unlock();
  };
   std::thread threads[5];
   for (int i = 0; i < 5; ++i) {
       threads[i] = std::thread(func1, 200);
  }
   for (auto& th : threads) {
       th.join();
  }
   return 0;
}


std::timed_mutex:


#include 
#include 
#include 
#include 

using namespace std;
std::timed_mutex timed_mutex_;

int main() {
   auto func1 = [](int k) {
       timed_mutex_.try_lock_for(std::chrono::milliseconds(200));
       for (int i = 0; i < k; ++i) {
           cout << i << " ";
      }
       cout << endl;
       timed_mutex_.unlock();
  };
   std::thread threads[5];
   for (int i = 0; i < 5; ++i) {
       threads[i] = std::thread(func1, 200);
  }
   for (auto& th : threads) {
       th.join();
  }
   return 0;
}


3
std::lock 相关

这里主要介绍两种RAII方式的锁封装,可以动态的释放锁资源,防止线程由于编码失误导致一直持有锁。


c++11主要有 std::lock_guard 和 std::unique_lock 两种方式,使用方式都类似,如下:


#include 
#include 
#include 
#include 

using namespace std;
std::mutex mutex_;

int main() {
   auto func1 = [](int k) {
       // std::lock_guard lock(mutex_);
       std::unique_lock<std::mutex> lock(mutex_);
       for (int i = 0; i < k; ++i) {
           cout << i << " ";
      }
       cout << endl;
  };
   std::thread threads[5];
   for (int i = 0; i < 5; ++i) {
       threads[i] = std::thread(func1, 200);
  }
   for (auto& th : threads) {
       th.join();
  }
   return 0;
}


std::lock_gurad 相比于 std::unique_lock 更加轻量级,少了一些成员函数,std::unique_lock 类有 unlock 函数,可以手动释放锁,所以条件变量都配合 std::unique_lock 使用,而不是 std::lock_guard 。


因为条件变量在 wait 时需要有手动释放锁的能力,具体关于条件变量后面会讲到。



4
std::atomic 相关

c++11 提供了原子类型 std::atomic,理论上这个 T 可以是任意类型,但是我平时只存放整形,别的还真的没用过,整形有这种原子变量已经足够方便,就不需要使用 std::mutex 来保护该变量啦。看一个计数器的代码:


struct OriginCounter { // 普通的计数器
   int count;
   std::mutex mutex_;
   void add() {
       std::lock_guard<std::mutex> lock(mutex_);
       ++count;
  }

   void sub() {
       std::lock_guard<std::mutex> lock(mutex_);
       --count;
  }

   int get() {
       std::lock_guard<std::mutex> lock(mutex_);
       return count;
  }
};

struct NewCounter { // 使用原子变量的计数器
   std::atomic<int> count;
   void add() {
       ++count;
       // count.store(++count);这种方式也可以
  }

   void sub() {
       --count;
       // count.store(--count);
  }

   int get() {
       return count.load();
  }
}


是不是使用原子变量更加方便了呢?




5
std::call_once 相关

c++11 提供了 std::call_once 来保证某一函数在多线程环境中只调用一次,它需要配合std::once_flag 使用,直接看使用代码:


std::once_flag onceflag;

void CallOnce() {
   std::call_once(onceflag, []() {
       cout << "call once" << endl;
  });
}

int main() {
   std::thread threads[5];
   for (int i = 0; i < 5; ++i) {
       threads[i] = std::thread(CallOnce);
  }
   for (auto& th : threads) {
       th.join();
  }
   return 0;
}



6
std::volatile 相关

貌似把 volatile 放在并发里介绍不太合适,但是貌似很多人都会把 volatile 和多线程联系在一起,那就一起介绍下吧。


volatile 通常用来建立内存屏障,volatile 修饰的变量,编译器对访问该变量的代码通常不再进行优化,看下面代码:


int *p = xxx;
int a = *p;
int b = *p;


a 和 b 都等于 p 指向的值,一般编译器会对此做优化,把 *p 的值放入寄存器,就是传说中的工作内存(不是主内存),之后 a 和 b 都等于寄存器的值。


但是如果中间 p 地址的值改变,内存上的值改变啦,但 a,  b 还是从寄存器中取的值(不一定,看编译器优化结果),这就不符合需求,所以在此对 p 加 volatile 修饰可以避免进行此类优化。



注意:volatile不能解决多线程安全问题,针对特种内存才需要使用volatile,它和atomic的特点如下:
 std::atomic用于多线程访问的数据,且不用互斥量,用于并发编程中
 volatile用于读写操作不可以被优化掉的内存,用于特种内存中


7
std::condition_variable 相关


条件变量是 c++11 引入的一种同步机制,它可以阻塞一个线程或者个线程,直到有线程通知或者超时才会唤醒正在阻塞的线程,条件变量需要和锁配合使用,这里的锁就是上面介绍的std::unique_lock。


这里使用条件变量实现一个 CountDownLatch :


class CountDownLatch {
   public:
    explicit CountDownLatch(uint32_t count) : count_(count);

    void CountDown() {
        std::unique_lock<std::mutex> lock(mutex_);
        --count_;
        if (count_ == 0) {
            cv_.notify_all();
        }
    }

    void Await(uint32_t time_ms = 0) {
        std::unique_lock<std::mutex> lock(mutex_);
        while (count_ > 0) {
            if (time_ms > 0) {
                cv_.wait_for(lock, std::chrono::milliseconds(time_ms));
            } else {
                cv_.wait(lock);
            }
        }
    }

    uint32_t GetCount() const {
        std::unique_lock<std::mutex> lock(mutex_);
      return count_;
    }

   private:
    std::condition_variable cv_;
    mutable std::mutex mutex_;
    uint32_t count_ = 0;
}


关于条件变量其实还涉及到通知丢失和虚假唤醒问题,因为不是本文的主题,这里暂不介绍,大家有需要可以留言。


8
std::future 相关

c++11关于异步操作提供了future相关的类,主要有 std::future、std::promise 和std::packaged_task ,std::future比std::thread 高级些,std::future 作为异步结果的传输通道,通过 get() 可以很方便的获取线程函数的返回值。


std::promise 用来包装一个值,将数据和 future 绑定起来,而 std::packaged_task 则用来包装一个调用对象,将函数和 future 绑定起来,方便异步调用。而 std::future 是不可以复制的,如果需要复制放到容器中可以使用 std::shared_future 。


std::promise与std::future配合使用


#include 
#include 
#include 
#include 

using namespace std;


void func(std::future<int>& fut) {
    int x = fut.get();
    cout << "value: " << x << endl;
}

int main() {
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread t(func, std::ref(fut));
    prom.set_value(144);
    t.join();
    return 0;
}


std::packaged_task 与 std::future 配合使用


#include 
#include 
#include 
#include 

using namespace std;

int func(int in) {
    return in + 1;
}

int main() {
    std::packaged_task<int(int)> task(func);
    std::future<int> fut = task.get_future();
    std::thread(std::move(task), 5).detach();
    cout << "result " << fut.get() << endl;
    return 0;
}


更多关于future的使用可以看我之前写的关于线程池和定时器的文章。

三者之间的关系

std::future 用于访问异步操作的结果,而 std::promise 和 std::packaged_task 在 future 高一层,它们内部都有一个 future,promise 包装的是一个值,packaged_task 包装的是一个函数。


当需要获取线程中的某个值,可以使用std::promise,当需要获取线程函数返回值,可以使用std::packaged_task。



9
async 相关

async 是比 future,packaged_task,promise 更高级的东西,它是基于任务的异步操作,通过async 可以直接创建异步的任务,返回的结果会保存在 future 中。


不需要像 packaged_task 和 promise 那么麻烦,关于线程操作应该优先使用 async,看一段使用代码:


#include 
#include 
#include 
#include 

using namespace std;

int func(int in) return in + 1; }

int main() {
    auto res = std::async(func, 5);
    // res.wait();
    cout << res.get() << endl// 阻塞直到函数返回
    return 0;
}


使用 async 异步执行函数是不是方便多啦。


async具体语法如下:


async(std::launch::async | std::launch::deferred, func, args...);


第一个参数是创建策略:


  • std::launch::async 表示任务执行在另一线程;

  • std::launch::deferred 表示延迟执行任务,调用 get 或者 wait 时才会执行,不会创建线程,惰性执行在当前线程。

如果不明确指定创建策略,以上两个都不是 async 的默认策略,而是未定义,它是一个基于任务的程序设计,内部有一个调度器(线程池),会根据实际情况决定采用哪种策略。


若从 std::async 获得的 std::future 未被移动或绑定到引用,则在完整表达式结尾, std::future的析构函数将阻塞直至异步计算完成,实际上相当于同步操作:


std::async(std::launch::async, []{ f(); }); // 临时量的析构函数等待 f()
std::async(std::launch::async, []{ g(); }); // f() 完成前不开始




注意:关于async启动策略这里网上和各种书籍介绍的五花八门,这里会以cppreference为主。

 有时候我们如果想真正执行异步操作可以对async进行封装,强制使用std::launch::async策略来调用async。


template <typename F, typename... Args>
inline auto ReallyAsync(F&& f, Args&&... params) {
    return std::async(std::launch::async, std::forward(f), std::forward(params)...);
}


10
总结




 std::thread使线程的创建变得非常简单,还可以获取线程id等信息。

 std::mutex通过多种方式保证了线程安全,互斥量可以独占,也可以重入,还可以设置互斥量的超时时间,避免一直阻塞等锁。

• std::lock通过RAII技术方便了加锁和解锁调用,有std::lock_guard和std::unique_lock。

• std::atomic提供了原子变量,更方便实现实现保护,不需要使用互斥量

• std::call_once保证函数在多线程环境下只调用一次,可用于实现单例。

• volatile常用于读写操作不可以被优化掉的内存中。

• std::condition_variable提供等待的同步机制,可阻塞一个或多个线程,等待其它线程通知后唤醒。

• std::future用于异步调用的包装和返回值。

• async更方便的实现了异步调用,异步调用优先使用async取代创建线程。


参考资料

https://blog.csdn.net/zhangzq86/article/details/70623394
https://zh.cppreference.com/w/cpp/atomic/atomic
https://zhuanlan.zhihu.com/p/33074506
https://www.runoob.com/w3cnote/c-volatile-keyword.html
https://zh.cppreference.com/w/cpp/thread/async
《深入应用c++11:代码优化与工程级应用》
《Effective Modern C++》



推荐:

面试常问的 C/C++ 问题,你能答上来几个?

C++ 面试必问:深入理解虚函数表

很多人搞不清 C++ 中的 delete 和 delete[ ] 的区别

看懂别人的代码,总得懂点 C++ lambda 表达式吧

Java、C++ 内存模型都不知道,还敢说自己是高级工程师?

C++ std::thread 必须要熟悉的几个知识点

现代 C++ 并发编程基础

现代 C++ 智能指针使用入门

c++ thread join 和 detach 到底有什么区别?

C++ 面试八股文:list、vector、deque 比较

C++经典面试题(最全,面中率最高)

C++ STL deque 容器底层实现原理(深度剖析)

STL vector push_back 和 emplace_back 区别

了解 C++ 多态与虚函数表

C++ 面试被问到的“左值引用和右值引用”
浏览 26
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报