C++11/14 線程中使用Lambda函數(shù)的方法
多線程中使用lambda
在本篇文章中,主要介紹lambda函數(shù)在多線程中的使用。
先從下面的例子開始吧:
#include <iostream>
#include <thread>
int main()
{
std::thread t([]()
{
std::cout << "thread function\n";
});
std::cout << "main thread\n";
t.join();
return 0;
}
在此基礎上我們將創(chuàng)建5個線程,然后把線程放進一個vector容器中, 用for_each()完成線程的匯合(join):
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
int main()
{
// vector 容器存儲線程
std::vector<std::thread> workers;
for (int i = 0; i < 5; i++)
{
workers.push_back(std::thread([]()
{
std::cout << "thread function\n";
}));
}
std::cout << "main thread\n";
// 通過 for_each 循環(huán)每一個線程
// 第三個參數(shù)賦值一個task任務
// 符號'[]'會告訴編譯器我們正在用一個匿名函數(shù)
// lambda函數(shù)將它的參數(shù)作為線程的引用t
// 然后一個一個的join
std::for_each(workers.begin(), workers.end(), [](std::thread &t;)
{
t.join();
});
return 0;
}
輸出應該像這樣:
thread function
thread function
thread function
thread function
thread function
main thread
vector容器包含個工作線程,然后在它們結束任務之后,與主線程匯合。
并發(fā)編程的不確定性
從上面的輸出中可以看出,我們無法分辨哪一個線程在打印。
因此,我們需要在每個線程上添加一個標記。鑒于我們使用lambda,所以我們可以嘗試下它的捕獲能力。
通過將i的值傳遞給線程,使用[i]我們可以將索引傳遞到線程函數(shù)中:
for (int i = 0; i < 5; i++)
{
workers.push_back(std::thread([i]()
{
std::cout << "thread function " << i << "\n";
}));
}
輸出:
thread function thread function thread function thread function thread function
main thread
4
2
1
0
3
每次運行的輸出可能不同,這體現(xiàn)了并發(fā)編程的不確定性性質。
此外,我們可以從輸出中看到,甚至在打印語句之間,也可以是搶占式的,換句話說,調度程序可以隨時中斷。
因此,由于當前編程的性質,我們使用lambda捕獲特性的努力沒有成功。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C/C++實現(xiàn)發(fā)送與接收HTTP/S請求的示例代碼
HTTP(Hypertext Transfer Protocol)是一種用于傳輸超文本的協(xié)議,它是一種無狀態(tài)的、應用層的協(xié)議,用于在計算機之間傳輸超文本文檔,通常在 Web 瀏覽器和 Web 服務器之間進行數(shù)據(jù)通信,本文給大家介紹了C/C++發(fā)送與接收HTTP/S請求,需要的朋友可以參考下2023-11-11
C語言當函數(shù)執(zhí)行成功時return1還是0
本文主要介紹了C語言當函數(shù)執(zhí)行成功時return1還是0,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

