刷算法题:
第一遍:1.看5分钟,没思路看题解
2.通过题解改进自己的解法,并且要写每行的注释以及自己的思路。
3.思考自己做到了题解的哪一步,下次怎么才能做对(总结方法)
4.整理到自己的自媒体平台。
5.再刷重复的类似的题目,根据时间和任务安排刷哪几个板块
6.用c++语言 都刷过一遍了 就刷中等
一.题目
c++写一个死锁并且自己解锁。
二、反思
1.死锁
#include<thread>
#include<mutex>using namespace std;mutex mutex1;
mutex mutex2;void thread1_deadlock(){lock_guard<mutex> lock1(mutex1);//创建的时候立即锁this_thread::sleepfor(chrono::milliseconds(100));lock_guard<mutex> lock2(mutex2);}void thread2_deadlock(){lock_guard<mutex> lock1(mutex2);this_thread::sleepfor(chrono::milliseconds(100));lock_guard<mutex> lock2(mutex1);
}int main(){thread t1(thread1_deadlock);thread t2(thread2_deadlock);t1.join();t2.join();return 0;
}
2.解锁
#include <iostream>
#include <thread>
#include <mutex>using namespace std;mutex mutex1;
mutex mutex2;void thread1_no_deadlock(){unique_lock<mutex> lock1(mutex1,defer_lock);//创建,但是先不锁unique_lock<mutex> lock2(mutex2,defer_lock);lock(lock1,lock2);//同时两个才能锁this_thread::sleep_for(chrono::seconds(1));}void thread2_no_deadlock(){unique_lock<mutex> lock1(mutex1,defer_lock);unique_lock<mutex> lock2(mutex2,defer_lock);lock(lock1,lock2);this_thread::sleep_for(chrono::seconds(1));
}int main(){thread t3(thread_no_deadlock);thread t4(thread_no_deadlock);t3.join();t4.join();return 0;
}