广州海珠做网站的公司,wordpress 视频无广告,网页制作与网站建设论文,上海网站建设安全0.死锁的由来
假设有两个线程T1和T2#xff0c;它们需要对两个互斥量mtx1和mtx2进行访问。而且需要按照以下顺序获取互斥量的所有权#xff1a; -T1先获取mte1的所有权,再获取mt2的所有权。 -T2先获取 mtx2的所有权。再铁取 mtx1的所有权。 如果两个线程同时执行#xff0c…0.死锁的由来
假设有两个线程T1和T2它们需要对两个互斥量mtx1和mtx2进行访问。而且需要按照以下顺序获取互斥量的所有权 -T1先获取mte1的所有权,再获取mt2的所有权。 -T2先获取 mtx2的所有权。再铁取 mtx1的所有权。 如果两个线程同时执行就会出现死锁问题。因为T1获取了mtx1的所有权但是无法获取mtx2的所有权而T2获取了mtx2的所有权但是无法获取 mtx1的所有权两个线程互相等待对方释放互斥量,导致死锁。
1.不同锁类型
类型类名作用超时锁timed_mutex避免长时间死锁递归锁recursive_mutex同一线程的同一锁可以锁多次避免死锁共享锁shared_mutex可以充分利用cpu资源
2.各种锁
2.1超时锁
①作用避免长时间死锁 ②性质可以记录锁获取情况多次超时可以记录日志获取错误情况。
#include iostream
#include thread
#include mutexstd::timed_mutex tmux;void ThreadMainTime(int i)
{for (;;){if (tmux.try_lock_for(std::chrono::microseconds(500))){std::cout i :[try_lock_for timeout] std::endl;continue;}std::cout [in] i std::endl;tmux.unlock();std::this_thread::sleep_for(std::chrono::microseconds(1));}
}int main()
{for (int i 0; i 3; i){std::thread th(ThreadMainTime, i 1);th.detach();}getchar();return 0;
}2.2递归锁
①作用同一线程的同一锁可以锁多次避免不必要的死锁。 ②性质组合业务用到同一个锁 注recursive_timed_mutex为递归超时锁 #include iostream
#include thread
#include mutexstd::recursive_mutex rmux;void Task1()
{rmux.lock();std::cout task1 [in] std::endl;rmux.unlock();
}void Task2()
{rmux.lock();std::cout task2 [in] std::endl;rmux.unlock();
}void ThreadMainRec(int i)
{for (;;){rmux.lock();Task1();std::cout i [in] std::endl;std::this_thread::sleep_for(std::chrono::microseconds(2000));Task2();rmux.unlock();}
}int main()
{for (int i 0; i 3; i){std::thread th(ThreadMainRec, i 1);th.detach();}getchar();return 0;
}2.3共享锁 #include iostream
#include thread
#include mutex
#include shared_mutexstd::shared_timed_mutex stmux;void ThreadRead(int i)
{for (;;){stmux.lock_shared();std::cout Read: i std::endl;std::this_thread::sleep_for(std::chrono::microseconds(3000));stmux.unlock_shared();std::this_thread::sleep_for(std::chrono::microseconds(1));}
}void ThreadWrite(int i)
{for (;;){stmux.lock_shared();stmux.unlock_shared();stmux.lock();std::cout Write: i std::endl;std::this_thread::sleep_for(std::chrono::microseconds(3000));stmux.unlock();std::this_thread::sleep_for(std::chrono::microseconds(1));}
}int main()
{for (int i 0; i 3; i){std::thread th(ThreadWrite, i 1);th.detach();}for (int i 0; i 3; i){std::thread th(ThreadRead, i 1);th.detach();}getchar();return 0;
}