多线程的锁
超时锁
可重入锁
共享锁
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
//Linux -lpthread
using namespace std;
timed_mutex tmux;
void ThreadMainTime(int i)
{
for (;;)
{
// 如果 500 ms 都没有获取到锁
if (!tmux.try_lock_for(chrono::milliseconds(500)))
{
cout << i << "[try_lock_for timeout]" << endl;
continue;
}
cout << i << "[in]" << endl;
this_thread::sleep_for(2000ms);
tmux.unlock();
this_thread::sleep_for(1ms);
}
}
int main(int argc, char* argv[])
{
for (int i = 0; i < 3; i++)
{
thread th(ThreadMainTime, i + 1);
th.detach();
}
getchar();
return 0;
}
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
//Linux -lpthread
using namespace std;
recursive_mutex rmux;
void Task1()
{
rmux.lock();
cout << "task1 [in]" << endl;
rmux.unlock();
}
void Task2()
{
rmux.lock();
cout << "task2 [in]" << endl;
rmux.unlock();
}
void ThreadMainRec(int i)
{
for (;;)
{
rmux.lock();
Task1();
cout << i << "[in]" << endl;
this_thread::sleep_for(2000ms);
Task2();
rmux.unlock();
this_thread::sleep_for(1ms);
}
}
int main(int argc, char* argv[])
{
for (int i = 0; i < 3; i++)
{
thread th(ThreadMainRec, i + 1);
th.detach();
}
getchar();
return 0;
}
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
#include <shared_mutex>
//Linux -lpthread
using namespace std;
//c++17 共享锁
//shared_mutex smux;
//c++14 共享锁
shared_timed_mutex stmux;
void ThreadRead(int i)
{
for (;;)
{
stmux.lock_shared();
cout << i << " Read" << endl;
this_thread::sleep_for(500ms);
stmux.unlock_shared();
this_thread::sleep_for(1ms);
}
}
void ThreadWrite(int i)
{
for (;;)
{
stmux.lock_shared();
// 读取数据
stmux.unlock_shared();
// 互斥锁 写入
stmux.lock();
cout << i << " Write" << endl;
this_thread::sleep_for(300ms);
stmux.unlock();
this_thread::sleep_for(1ms);
}
}
int main(int argc, char* argv[])
{
for (int i = 0; i < 3; i++)
{
thread th(ThreadWrite, i + 1);
th.detach();
}
for (int i = 0; i < 3; i++)
{
thread th(ThreadRead, i + 1);
th.detach();
}
getchar();
return 0;
}