|
- unique_lock功能比lock_gard更加灵活强大,缺点是使用成本更高一些。
复制代码- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <vector>
- #include <chrono>
- std::timed_mutex g_timed_mutex;
- void func(int val)
- {
- std::unique_lock<decltype(g_timed_mutex)> lockguard(g_timed_mutex,std::defer_lock);
- //std::cout<<std::this_thread::get_id()<<"owns the lock... "<<lockguard.owns_lock()<<std::endl;
- while(!lockguard.try_lock_for(std::chrono::seconds(val)))
- {
- std::cout<<std::this_thread::get_id()<<" failed to access the lock..."<<std::endl;
- //return;
- }
- std::cout<<"now, "<<std::this_thread::get_id()<<" owns the lock..."<<lockguard.owns_lock()<<std::endl;
- std::this_thread::sleep_for(std::chrono::seconds(val));
- }
- int main()
- {
- std::vector<std::thread> vec_threads;
- for(int i = 0; i<10; i++)
- {
- std::thread th(func,i+1);
- vec_threads.push_back(std::move(th));
- }
- for(int i =0; i<vec_threads.size();i++)
- {
- if(vec_threads[i].joinable())
- {
- vec_threads[i].join();
- }
- }
- std::cout<<"program ends..."<<std::endl;
- }
复制代码
|
|