标签:
1、 头文件。
2、std::mutex。
std::mutex 的成员函数
#include //std::cout#include //std::thread#include //std::mutex#include //std::atomicusing namespace std;atomic_int counter{ 0 }; //原子变量mutex g_mtx; //互斥量void fun() {for (int i = 0; i <</span> 1000000; ++i){if (g_mtx.try_lock()) //尝试是否可以加锁{++counter;g_mtx.unlock(); //解锁}}}int main(){thread threads[10];for (int i = 0; i <</span> 10; ++i){threads[i] = thread(fun);}for (auto & th : threads){th.join();}cout << "counter=" << counter << endl;system("pause");return 0;}运行结果:counter=13422443、std::recursive_mutex。
#include //std::cout#include //std::thread#include //std::mutexusing namespace std;mutex g_mutex;void threadfun1(){cout << "enter threadfun1" << endl;lock_guard lock(g_mutex);cout << "execute threadfun1" << endl;}void threadfun2(){cout << "enter threadfun2" << endl;lock_guard lock(g_mutex);threadfun1();cout << "execute threadfun2" << endl;}int main(){threadfun2(); //死锁//Unhandled exception at 0x758BC42D in Project2.exe: Microsoft C++ exception: std::system_error at memory location 0x0015F140.return 0;}运行结果:enter threadfun2enter threadfun1//就会产生死锁#include //std::cout#include //std::thread#include //std::mutexusing namespace std;recursive_mutex g_rec_mutex;void threadfun1(){cout << "enter threadfun1" << endl;lock_guard lock(g_rec_mutex);cout << "execute threadfun1" << endl;}void threadfun2(){cout << "enter threadfun2" << endl;lock_guard lock(g_rec_mutex);threadfun1();cout << "execute threadfun2" << endl;}int main(){threadfun2(); //利用递归式互斥量来避免这个问题return 0;}运行结果:enter threadfun2enter threadfun1execute threadfun1execute threadfun24、std::time_mutex。
#include //std::cout#include //std::thread#include //std::mutexusing namespace std;std::timed_mutex g_t_mtx;void fun(){while (!g_t_mtx.try_lock_for(std::chrono::milliseconds(200))){cout << "-";}this_thread::sleep_for(std::chrono::milliseconds(1000));cout << "*" << endl;g_t_mtx.unlock();}int main(){std::thread threads[10];for (int i = 0; i <</span> 10; i++){threads[i] = std::thread(fun);}for (auto & th : threads){th.join();}return 0;}运行结果:------------------------------------*----------------------------------------*-----------------------------------*------------------------------*-------------------------*--------------------*---------------*----------*-----**5、std::lock_guard 与 std::unique_lock。
#include //std::cout#include //std::thread#include //std::mutex#include //std::atomicusing namespace std;mutex g_mtx1;atomic_int num1{ 0 };void fun1(){for (int i = 0; i <</span> 10000000; i++){unique_lock ulk(g_mtx1);num1++;}}mutex g_mtx2;atomic_int num2{ 0 };void fun2(){for (int i = 0; i <</span> 10000000; i++){lock_guard lckg(g_mtx2);num2++;}}int main(){thread th1(fun1);thread th2(fun1);th1.join();th2.join();cout << "num1=" << num1 << endl;thread th3(fun2);thread th4(fun2);th3.join();th4.join();cout << "num2=" << num2 << endl;return 0;}运行结果:num1=20000000num2=20000000标签:
原文地址:http://www.cnblogs.com/iihcy/p/5116188.html