C++多線程編程和同步機制實例演示
多線程編程基礎(chǔ)
在C++中,使用<thread>
庫來創(chuàng)建和管理線程。線程可以通過函數(shù)、成員函數(shù)或者Lambda
表達式來實現(xiàn)。
以下是一個使用Lambda
表達式來創(chuàng)建線程的例子:
#include <thread> #include <iostream> int main() { std::thread t([](){ std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; }); t.join(); return 0; }
上述代碼創(chuàng)建了一個線程并輸出了該線程的ID
。在創(chuàng)建線程時,需要將線程函數(shù)作為參數(shù)傳遞給std::thread
。
在上述例子中,我們使用了Lambda
表達式來定義線程函數(shù),該表達式會輸出一行文本。
同步機制
多線程編程中最常見的問題是數(shù)據(jù)競爭和死鎖。為了避免這些問題,我們需要使用同步機制來控制線程的訪問。
互斥量
互斥量是C++中最常用的同步機制之一?;コ饬靠梢员WC同一時間只有一個線程可以訪問共享資源。
以下是一個使用互斥量來保護共享資源的例子:
#include <thread> #include <mutex> #include <iostream> std::mutex mtx; void thread_func() { mtx.lock(); std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; mtx.unlock(); } int main() { std::thread t1(thread_func); std::thread t2(thread_func); t1.join(); t2.join(); return 0; }
上述代碼創(chuàng)建了兩個線程,并使用互斥量來保護共享資源。在線程函數(shù)中,我們先調(diào)用mtx.lock()
函數(shù)來鎖定互斥量,然后訪問共享資源,最后再調(diào)用mtx.unlock()
函數(shù)來釋放互斥量。
在上述例子中,我們使用了兩個線程來訪問共享資源,但是只有一個線程可以訪問該資源。
這是因為在一個線程訪問共享資源時,該資源會被鎖定,其他線程無法訪問該資源,直到該線程釋放互斥量為止。
條件變量
條件變量是C++中另一個常用的同步機制。條件變量可以讓線程在某些條件滿足時才繼續(xù)執(zhí)行,否則就等待。
以下是一個使用條件變量來同步線程的例子:
#include <thread> #include <mutex> #include <condition_variable> #include <iostream> std::mutex mtx; std::condition_variable cv; bool ready = false; void consumer() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [](){ return ready; }); std::cout << "Hello from consumer thread " << std::this_thread::get_id() << std::endl; } void producer() { std::this_thread::sleep_for(std::chrono::seconds(1)); ready = true; cv.notify_one(); } int main() { std::thread t1(consumer); std::thread t2(producer); t1.join(); t2.join(); return 0; }
上述代碼創(chuàng)建了兩個線程,一個生產(chǎn)者線程和一個消費者線程。生產(chǎn)者線程在1秒后將ready
變量設(shè)置為true
,然后通知消費者線程繼續(xù)執(zhí)行。
消費者線程等待條件變量cv
,直到ready
變量的值為true
為止。
在該例子中,我們使用了條件變量來同步生產(chǎn)者和消費者線程。
結(jié)論
多線程編程和同步機制是C++中非常重要的主題。本文介紹了多線程編程的基本概念和使用方法,以及互斥量和條件變量等常用的同步機制。
希望這篇文章對你有所幫助,更多關(guān)于C++多線程同步機制的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于STL中l(wèi)ist容器的一些總結(jié)
list就是數(shù)據(jù)結(jié)構(gòu)中的雙向鏈表(根據(jù)sgi stl源代碼),因此它的內(nèi)存空間是不連續(xù)的,通過指針來進行數(shù)據(jù)的訪問,這個特點使得它的隨即存取變的非常沒有效率,因此它沒有提供[]操作符的重載2013-09-09