C++的线程std::thread,互斥量std::mutex,锁lock,原子操作atomic,条件变量condition_variable

/ 0评 / 0
void foo(Cpp11* p, int n) {
    // std::unique_lock<std::mutex> lock(p->m_wait_mutex);
    std::this_thread::sleep_for(std::chrono::seconds(n));
    p->m_cv.notify_one();
    std::cout << R"(foo)" << std::this_thread::get_id() << std::endl;

    {
        // 互斥量
        g_mutex.lock();
        bool lock_suc = g_mutex.try_lock();

        g_mutex.unlock();
        g_mutex.unlock();
    }

    {
        // 锁
        g_mutex.lock();
        std::lock_guard<std::mutex> my_lock_guard(g_mutex, std::adopt_lock); // 接管之前的lock()
        std::unique_lock<std::mutex> my_lock(g_mutex, std::adopt_lock); // 接管之前的lock()

        std::unique_lock<std::mutex> my_lock1(g_mutex, std::defer_lock); // 延迟lock
        my_lock1.lock(); // 手动lock
        my_lock1.unlock(); // 手动unlock,也可以不调用,结束后自动unlock
        bool try_lock_suc = my_lock1.try_lock(); // 尝试加锁,非阻塞,成功或失败

        std::unique_lock<std::mutex> my_lock2(g_mutex, std::try_to_lock); // 尝试lock,立即返回
        if (my_lock2.owns_lock()) {
            // lock成功
        } else {
            // lock失败
        }
        std::mutex* my_mutex = my_lock2.release(); // 释放所有权,手动接管
        // std::unique_lock<std::mutex> my_lock3(my_lock2); // unique_lock不能复制
    }
    
    {
        // 原子操作atomic
        std::atomic<int> ia;
        ia.store(10);
        ia = 11;
        int va = ia.load();
        int vb = ia.exchange(100);
        int expected = 100;
        bool ex = ia.compare_exchange_weak(expected, 200);
        int new_va = ia.load();
        expected = 200;
        bool ex1 = ia.compare_exchange_strong(expected, 300);
        int new_va1 = ia.load();
    }
}

// 线程
    std::thread t = std::thread(foo, this, 5);
    // t.join();
    t.detach();
    std::cout << R"(main)" << std::this_thread::get_id() << std::endl;
    
    std::unique_lock<std::mutex> lock(m_wait_mutex);
    m_cv.wait(lock, []() {
        return 10;
    });