C++11新特性之线程相关所有知识点

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

  • std::thread相关
  • std::mutex相关
  • std::lock相关
  • std::atomic相关
  • std::call_once相关
  • volatile相关
  • std::condition_variable相关
  • std::future相关
  • async相关

std::thread相关

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

#include <iostream>
#include <thread>

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;
}

上述代码中,函数 funcfunc1 运行在线程对象 ttt 中,从刚创建对象开始就会新建一个线程用于执行函数。调用 join() 函数将会阻塞主线程,直到线程函数执行结束,线程函数的返回值将会被忽略。如果不希望线程被阻塞执行,可以调用线程对象的 detach() 函数,表示将线程和线程对象分离。

如果没有调用 join()detach() 函数,假如线程函数执行时间较长,此时线程对象的生命周期结束调用析构函数清理资源,这时可能会发生错误。这里有两种解决办法,一个是调用 join(),保证线程函数的生命周期和线程对象的生命周期相同,另一个是调用 detach(),将线程和线程对象分离。需要注意,如果线程已经和对象分离,那么就再也无法控制线程何时结束,不能再通过 join() 来等待线程执行完。

为了避免没有调用 join()detach() 可导致程序出错的情况,可以对 std::thread 进行封装,以确保线程资源得到正确释放:

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));

std::mutex相关

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

C++标准库提供了四种不同种类的互斥量,包括:

  • std::mutex:独占的互斥量,不支持递归使用,不带超时功能。
  • std::recursive_mutex:递归互斥量,支持可重入,不带超时功能。
  • std::timed_mutex:带超时功能的互斥量,不支持递归。
  • std::recursive_timed_mutex:带超时功能的互斥量,支持递归使用。

这些互斥量类型可以根据具体的多线程应用场景来选择,以确保线程安全和避免死锁等问题。

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

std::mutex:

#include <iostream>
#include <mutex>
#include <thread>

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 <iostream>
#include <mutex>
#include <thread>
#include <chrono>

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;
}

std::lock相关

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

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

#include <iostream>
#include <mutex>
#include <thread>
#include <chrono>

using namespace std;
std::mutex mutex_;

int main() {
    auto func1 = [](int k) {
        // std::lock_guard<std::mutex> 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_guard 相对于 std::unique_lock 更加轻量级,它少了一些成员函数。std::unique_lock 类有 unlock 函数,可以手动释放锁,因此在使用条件变量时通常配合 std::unique_lock 使用,而不是 std::lock_guard。这是因为条件变量在等待时需要有手动释放锁的能力,后面会详细讲解条件变量的使用。

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();
    }
};

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

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;
}

volatile相关

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

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

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

ab 都等于 p 指向的值,通常编译器会对此做优化,将 *p 的值放入寄存器,即传统的工作内存(不是主内存)。后续 ab 都等于寄存器中的值。但如果中间 p 地址的值发生更改,内存上的值发生变化,但 ab 仍然获取寄存器中的值(具体情况取决于编译器的优化)。这可能与需求不符,因此在此对 p 添加 volatile 修饰可以避免执行此类优化。

注意:volatile 不能解决多线程安全问题,针对特种内存才需要使用 volatile,它和 atomic 的特点如下:

  • std::atomic 用于多线程访问的数据,且不用互斥量,用于并发编程中
  • volatile 用于读写操作不可以被优化掉的内存,用于特种内存中

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;
}; 

std::future相关

C++11关于异步操作提供了future相关的类,主要有 std::futurestd::promisestd::packaged_taskstd::futurestd::thread 高级些,std::future 作为异步结果的传输通道,通过 get() 可以很方便的获取线程函数的返回值,std::promise 用来包装一个值,将数据和 future 绑定起来,而 std::packaged_task 则用来包装一个调用对象,将函数和 future 绑定起来,方便异步调用。而 std::future 是不可以复制的,如果需要复制放到容器中可以使用 std::shared_future

std::promisestd::future 配合使用:

#include <functional>
#include <future>
#include <iostream>
#include <thread>

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_taskstd::future配合使用:

#include <functional>
#include <future>
#include <iostream>
#include <thread>

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;
}

三者之间的关系

  • std::future 用于访问异步操作的结果,而 std::promisestd::packaged_taskstd::future 高一层,它们内部都有一个 futurestd::promise 包装的是一个值,std::packaged_task 包装的是一个函数。当需要获取线程中的某个值,可以使用 std::promise,当需要获取线程函数返回值,可以使用 std::packaged_task

async相关

async 是比 futurepackaged_taskpromise 更高级的东西,它是基于任务的异步操作。通过 async 可以直接创建异步的任务,返回的结果会保存在 future 中,不需要像 packaged_taskpromise 那么麻烦。关于线程操作,应该优先使用 async。以下是一段使用示例代码:

#include <functional>
#include <future>
#include <iostream>
#include <thread>

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::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>(f),
                        std::forward<Args>(params)...);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

川峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值