📌 讓程式同時進行多項任務
你一邊下載影片,一邊聽音樂,這就是並行
用 std::thread
來建立多個執行緒(threads),讓 CPU 同時處理不同工作
#include <iostream>
#include <thread>
using namespace std;
void work1()
{
for (int i = 0; i < 5; ++i)
{
cout << "慢數:" << i << endl;
}
}
void work2()
{
for (int i = 0; i < 5; ++i)
{
cout << "快數:" << i << endl;
}
}
int main()
{
thread t1(work1);
thread t2(work2);
t1.join();
t2.join();
cout << "都完成了!" << endl;
}
📌 thread t1(work1);
:啟動一個執行緒執行 work1()
📌 t1.join();
:等待該執行緒結束,否則主程式會提早結束
#include <iostream>
#include <thread>
using namespace std;
int main()
{
thread t([]
{
for (int i = 0; i < 3; ++i) cout << "執行中:" << i << endl;
});
cout << "繼續中..." << endl;
t.join();
}
📌 Lambda 可以讓程式更簡潔,適合簡單任務
📌 多執行緒有時會「搶資料」,造成混亂
為了避免衝突,我們用 互斥鎖 (mutex) 來保護共享資源
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int counter = 0;
mutex mtx;
void add_count()
{
for (int i = 0; i < 1000; ++i)
{
lock_guard<mutex> lock(mtx);
++counter;
}
}
int main()
{
thread t1(add_count);
thread t2(add_count);
t1.join();
t2.join();
cout << "結果:" << counter << endl;
}
📌 若沒有 mutex,結果可能亂掉
📌 C++11 提供 std::async
讓你輕鬆執行背景任務
#include <iostream>
#include <future>
using namespace std;
int slow_add(int a, int b)
{
this_thread::sleep_for(chrono::seconds(2));
return a + b;
}
int main()
{
future<int> result = async(slow_add, 3, 5);
cout << "運算中...先做別的事\n";
cout << "結果:" << result.get() << endl;
}
📌 .get()
會等結果完成後才取出。
📌 讓程式同時執行多項任務,提升速度與效率
std::thread
,我們可以建立多個工作執行緒
搭配 mutex
能避免資料衝突
async
與 future
則讓非同步運算更簡單,適合背景工作或 I/O 操作