溫馨提示×

c++ thread的用法有哪些

c++
小億
118
2023-10-09 04:29:37
欄目: 編程語言

C++中的線程庫提供了多種方式來創建和管理線程。以下是一些常見的C++線程用法:

  1. 使用std::thread類創建線程:
#include <iostream>
#include <thread>
void foo() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(foo);  // 創建一個新線程,并執行foo()函數
t.join();  // 等待線程t執行完畢
return 0;
}
  1. 使用lambda表達式創建線程:
#include <iostream>
#include <thread>
int main() {
std::thread t([]() {
std::cout << "Hello from thread!" << std::endl;
});
t.join();
return 0;
}
  1. 使用std::async函數創建異步任務:
#include <iostream>
#include <future>
int foo() {
return 42;
}
int main() {
std::future<int> result = std::async(foo);  // 創建一個異步任務,并返回一個std::future對象
std::cout << "Result: " << result.get() << std::endl;  // 獲取異步任務的結果
return 0;
}
  1. 使用std::mutex和std::lock_guard實現線程安全:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void foo() {
std::lock_guard<std::mutex> lock(mtx);  // 獲取互斥鎖
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(foo);
t.join();
return 0;
}

這些只是C++線程的一些常見用法,還有其他更高級的用法,如線程間的通信、線程池等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女