#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
mutex mu;
void ThreadSource(int i)
{
mu.lock();
cout << "線程" << i << "開始執行了" << endl;
std::this_thread::sleep_for(1s);
mu.unlock();
std::this_thread::sleep_for(3ms); //如果不加延時可能會造成線程資源來不及釋放
}
int main(int argc,char* argv[])
{
for (int i = 0; i < 10; i++)
{
std::thread th(ThreadSource,i+1);
th.detach();
}
getchar();
return 0;
}
超時鎖
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
timed_mutex mu;
void ThreadSource(int i)
{
for (;;)
{
if (!mu.try_lock_for(chrono::milliseconds(500ms)))
{
//如果未在規定時間內拿到鎖,那么這段代碼可能會出現問題,這里可以進行日志的寫入,便於調試
cout << "線程"<<i<<"超時"<<endl;
}
cout << "線程" << i << "開始執行了" << endl;
std::this_thread::sleep_for(1s);
mu.unlock();
std::this_thread::sleep_for(3ms); //如果不加延時可能會造成線程資源來不及釋放
}
}
int main(int argc,char* argv[])
{
for (int i = 0; i < 10; i++)
{
std::thread th(ThreadSource,i+1);
th.detach();
}
getchar();
return 0;
}