看完了b站上的c++多线程视频,这里留作记录。
创建、销毁线程
在c++11中,一般使用thread创建线程,传入入口函数和参数,如果是类成员函数,要传入对象,后面才是参数。传入的对象为引用,那么最好用join等待线程运行完成,不推荐用detach。线程参数推荐传入值,防止主线程先将对象析构。
ADD
: 可以通过指定CPU核心的方式,加快多线程速度,但是得注意NUMA。参考类似的博客,通过thread对象的native_handle
方法获取的id等价于pthread_t,这样就可以轻松调用pthread系列的函数了,下面是一个指定该线程运行到核1上的方法:
thread t;
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(1, &cpu_set);
int rc = pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set), &cpu_set);
if (rc != 0) {
printf("Error!\n");
}
对线程、入口函数的包装
由于直接使用thread创建线程,在资源紧张的情况下,程序由于无法创建线程会发生崩溃。需要添加future
头文件,使用async
创建异步任务,安全性更好。async
存在两个参数:std::launch::async
和std::launch::deferred
。async会强制创建线程,类似thread,deferred是先不创建,在使用get或wait时才运行,类似函数调用,由主线程执行,默认是std::launch::async | std::launch::deferred
,和不添加参数一样,系统资源充足创建线程,否则不创建线程。
future用来获取异步任务的返回值,调用get
或者wait
时等待任务运行完,获得最终的返回值。入口函数使用std::packaged_task<>
进行包装,灵活性比async
更高,将入口函数和线程创建分开,使用get_future
获取返回值future,而async
函数只有在调用的时候,利用返回值获得future。
线程同步
有互斥量mutex和条件变量condition_variable。mutex是对一段程序进行保护,使用lock
和unlock
进行加锁和解锁,为了防止忘记解锁,一般使用lock_guard
或者unique_lock
进行自动解锁,这两个的区别就是unique_lock
更灵活,除了adopt_lock
外,还有try_to_lock
和deferred_lock
,可以自己手动unlock。condition_variable常用函数有wait, notify_one, notify_all
,改进轮询模式,手动唤醒线程。
还有原子操作atomic,用于变量,功能有限,只支持少量operator,主要用于计数。
例子
参考基于C++11的线程池(threadpool),简洁且可以带任意多的参数。
文件:threadpool.h
#pragma once
#define __NAMESPACE_BEGIN namespace jw {
#define __NAMESPACE_END }
#include <iostream>
#include <future>
#include <vector>
#include <queue>
#include <functional>
#include <atomic>
#include <memory>
__NAMESPACE_BEGIN
using std::cout;
using std::endl;
// 100~200 is better
#define MAX_POOL_NUM 200
class ThreadPool {
public:
ThreadPool(unsigned pool_num = 5) : stop_(false) {
free_pool_num_ = pool_num < 1 ? 1 :
(pool_num < MAX_POOL_NUM ? pool_num : MAX_POOL_NUM);
for (pool_num = 0; pool_num < free_pool_num_; ++pool_num) {
// emplace_back和commit函数中的emplace,直接传入参数,减少拷贝
pool_.emplace_back([this] {
std::function<void()> task;
while (!stop_) {
{
// 从队列中取任务,加锁,用条件变量等待
std::unique_lock<std::mutex> lock(m_lock_);
// wait第二个参数用函数,不要空着,防止发生虚假唤醒
cv_lock_.wait(lock,
// 只有当线程池未停止,且任务为空时阻塞
[this] { return stop_ || !tasks_.empty(); });
// 线程池停止
if (stop_) return;
task = std::move(tasks_.front());
tasks_.pop();
}
cout << std::this_thread::get_id() << " 线程取得任务" << endl;
// 取得任务后,执行
--free_pool_num_;
task();
++free_pool_num_;
}
});
}
}
~ThreadPool()
{
stop_.store(true);
cv_lock_.notify_all();
// 防止报错,创建thread线程后,必须使用join或者detach
for (auto& t : pool_)
if (t.joinable())
t.join();
}
template<typename F, typename ...Args>
auto commit(F&& f, Args&&... args){
if (stop_) { throw std::runtime_error( "thread pool is stopped."); }
using return_type = decltype(f(args...));
// 不加make_shared,报错 C2280:尝试引用已删除函数
auto task = std::make_shared<std::packaged_task<return_type()>>(
// bind函数是用的复制值,所以c++11专门有个ref,
// 用于传入引用,返回类型为reference_wrapper
std::bind(std::ref(f), std::ref(args...))
);
std::future<return_type> ret = task->get_future();
// 添加到任务,没有返回值
{
std::lock_guard<std::mutex> lock(m_lock_);
tasks_.emplace([task] {
(*task)();
});
}
cv_lock_.notify_one();
return ret;
}
private:
std::queue<std::function<void()>> tasks_;
std::vector<std::thread> pool_;
std::mutex m_lock_;
std::condition_variable cv_lock_;
std::atomic<bool> stop_;
std::atomic<unsigned> free_pool_num_;
};
__NAMESPACE_END
文件:main.cpp
#include <iostream>
#include "threadpool.h"
using std::cout;
using std::endl;
std::mutex out_lock;
int print(int i) {
{
std::lock_guard<std::mutex> lock(out_lock);
std::cout << "sub thread: " << std::this_thread::get_id() << ", i is " << i << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(3));
return i + 3;
}
int main(int argc, char* argv[]) {
// 测试,只有三个线程,但有5个任务
jw::ThreadPool tt(3);
std::future<int>ret1 = tt.commit(print, 3);
std::future<int>ret2 = tt.commit(print, 4);
std::future<int>ret3 = tt.commit(print, 5);
std::future<int>ret4 = tt.commit(print, 6);
std::future<int>ret5 = tt.commit(print, 7);
cout << ret1.get() << ret2.get() << ret3.get() << ret4.get() << ret5.get() << endl;
return 0;
}
输出:
16248 线程取得任务3228 线程取得任务1664 线程取得任务
sub thread: 1664, i is 4
sub thread: 16248, i is 3
sub thread: 3228, i is 5
6781664 线程取得任务
sub thread: 1664, i is 6
3228 线程取得任务
sub thread: 3228, i is 7
910