c++多個線程函數(shù)對同一變量操作,如何枷鎖
每個線程用不同的線程函數(shù)
例如:
std::mutex mutex_;
void func1()
{
??? std::cout << "func1" << std::endl;
??? std::lock_guard<std::mutex> lck(mutex_);
??? std::this_thread::sleep_for(std::chrono::seconds(7));
??? std::cout << "func1 end" << std::endl;
}
void func2()
{
??? std::cout << "func2" << std::endl;
??? std::lock_guard<std::mutex> lck(mutex_);
??? std::cout << "func2 coming" << std::endl;
??? std::this_thread::sleep_for(std::chrono::seconds(3));
??? std::cout << "func2 end" << std::endl;
}
int main()
{
??? std::thread t1(func1);
??? std::this_thread::sleep_for(std::chrono::seconds(2));
??? std::thread t2(func2);
??? std::this_thread::sleep_for(std::chrono::seconds(15));
}
由于我們在定義t1線程后,休眠了2秒,則基本可以保證:func1函數(shù) 執(zhí)行到定義鎖且到了睡眠7秒的地方了,此時線程2才開始,
由于線程1先獲取到鎖且睡眠7秒,因此:線程2必須等7秒后才能輸出 func2 coming

多個線程公用一個線程函數(shù)
int counter = 0;
void increase(int count) {
??? for (size_t i = 0; i < count; i++)
??? {
??????? /*std::lock_guard<std::mutex> lck(mutex_);*/
??????? std::this_thread::sleep_for(std::chrono::milliseconds(1));
??????? counter++;
??? }
}測試:std::thread t1(increase, 5000);
??? std::thread t2(increase, 5000);
??? t1.join();
??? t2.join();
??? std::this_thread::sleep_for(std::chrono::seconds(5));
??? std::cout << "counter:" << counter << std::endl;結(jié)果:counter值并不是10000,說明了2個線程函數(shù)執(zhí)行時有對同counter變量修改存在問題,執(zhí)行3次結(jié)果都不同:



于是:通過枷鎖,來實現(xiàn)互斥訪問:
for (size_t i = 0; i < count; i++)
??? {
??????? std::lock_guard<std::mutex> lck(mutex_);
??????? std::this_thread::sleep_for(std::chrono::milliseconds(1));
??????? counter++;
??? }執(zhí)行3次結(jié)果如下,均為10000:



當然了,也可以在2個線程函數(shù)里執(zhí)行,枷鎖后效果一樣的。