您好,登錄后才能下訂單哦!
C++標(biāo)準(zhǔn)庫中提供了一些用于多線程編程的類和函數(shù),主要包括以下幾個部分:
#include <thread>
void myFunction() {
// 線程執(zhí)行的函數(shù)
}
int main() {
std::thread t(myFunction);
t.join(); // 等待線程執(zhí)行完成
return 0;
}
#include <thread>
#include <mutex>
std::mutex mtx;
void myFunction() {
std::lock_guard<std::mutex> lock(mtx);
// 訪問共享資源的代碼
}
int main() {
std::thread t1(myFunction);
std::thread t2(myFunction);
t1.join();
t2.join();
return 0;
}
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void myFunction() {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) {
cv.wait(lock);
}
// 可以繼續(xù)執(zhí)行
}
int main() {
std::thread t(myFunction);
// 喚醒線程
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
t.join();
return 0;
}
除了標(biāo)準(zhǔn)庫中提供的類和函數(shù),C++11之后還引入了并行算法庫(Parallel Algorithms),可以方便地進行并行計算。這些算法會自動利用多線程來加速計算,無需手動管理線程。
#include <algorithm>
#include <vector>
#include <execution>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5};
// 使用并行算法對容器進行排序
std::sort(std::execution::par, vec.begin(), vec.end());
return 0;
}
總的來說,C++標(biāo)準(zhǔn)庫提供了豐富的多線程編程工具,可以方便地實現(xiàn)并發(fā)編程。同時,也可以借助第三方庫(如Boost.Thread)來擴展多線程功能。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。