線程編程是一種允許程序并發(fā)執(zhí)行多個(gè)任務(wù)的技術(shù)。在C++中,線程編程可以通過使用C++11標(biāo)準(zhǔn)庫中的頭文件來實(shí)現(xiàn)。線程編程的應(yīng)用非常廣泛,可以用于提高程序的性能和響應(yīng)速度,同時(shí)處理多個(gè)用戶請求,執(zhí)行后臺任務(wù)等。
下面是一個(gè)簡單的C++線程編程的例子,演示如何在程序中創(chuàng)建和運(yùn)行多個(gè)線程:
#include <iostream>#include <thread>void print_numbers(int start, int end) { for (int i = start; i <= end; i++) { std::cout << i << " "; } std::cout << std::endl;}int main() { std::thread t1(print_numbers, 1, 10); std::thread t2(print_numbers, 11, 20); t1.join(); t2.join(); return 0;}
在上面的例子中,我們定義了一個(gè)函數(shù)print_numbers,用于打印一組數(shù)字。然后我們在main函數(shù)中創(chuàng)建了兩個(gè)線程t1和t2,分別調(diào)用print_numbers函數(shù)打印不同的數(shù)字范圍。最后,我們通過調(diào)用t1.join()和t2.join()等待兩個(gè)線程執(zhí)行完畢,然后返回主線程。
注意點(diǎn):
下面是一個(gè)使用互斥鎖和條件變量實(shí)現(xiàn)線程同步的例子:
#include <iostream>#include <thread>#include <mutex>#include <condition_variable>std::mutex mtx;std::condition_variable cv;int count = 0;void increment() { for (int i = 0; i < 100000; i++) { std::unique_lock<std::mutex> lock(mtx); count++; cv.notify_all(); lock.unlock(); std::this_thread::yield(); // 讓出CPU,等待其他線程執(zhí)行 }}void wait_for_count() { std::unique_lock<std::mutex> lock(mtx); while (count < 100000) { cv.wait(lock); // 等待條件滿足(count >= 100000)或者收到通知(cv.notify_all()) } std::cout << "count = " << count << std::endl;}int main() { std::thread t1(increment); std::thread t2(wait_for_count); t1.join(); t2.join(); return 0;}
在上面的例子中,我們定義了一個(gè)全局變量count和一個(gè)互斥鎖mtx和一個(gè)條件變量cv。在increment函數(shù)中,我們使用互斥鎖保護(hù)count變量,每次將count加1并通知所有等待的線程(cv.notify_all())。在wait_for_count函數(shù)中,我們使用互斥鎖和條件變量等待count變量達(dá)到100000。最后,我們在main函數(shù)中創(chuàng)建了兩個(gè)線程t1和t2分別執(zhí)行increment和wait_for_count函數(shù),然后等待兩個(gè)線程執(zhí)行完畢。
本文鏈接:http://www.www897cc.com/showinfo-26-17167-0.htmlC++中線程編程的應(yīng)用,注意點(diǎn),源代碼解析
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: 如何釋放React?Hooks的力量
下一篇: RabbitMQ的四種交換機(jī)詳解