C++多線程之互斥鎖和超時鎖


#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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM