c++ " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c++ thread鐨勭敤娉曟湁鍝簺

扬州沐宇科技
2023-10-09 04:29:37
c++

C++涓殑绾跨▼搴撴彁渚涗簡澶氱鏂瑰紡鏉ュ垱寤哄拰绠$悊绾跨▼銆備互涓嬫槸涓€浜涘父瑙佺殑C++绾跨▼鐢ㄦ硶锛?/p>

  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鍑芥暟鍒涘缓寮傛浠诲姟锛?/li>
#include <iostream>
#include <future>
int foo() {
return 42;
}
int main() {
std::future<int> result = std::async(foo);  // 鍒涘缓涓€涓紓姝ヤ换鍔★紝骞惰繑鍥炰竴涓猻td::future瀵硅薄
std::cout << "Result: " << result.get() << std::endl;  // 鑾峰彇寮傛浠诲姟鐨勭粨鏋?/span>
return 0;
}
  1. 浣跨敤std::mutex鍜宻td::lock_guard瀹炵幇绾跨▼瀹夊叏锛?/li>
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void foo() {
std::lock_guard<std::mutex> lock(mtx);  // 鑾峰彇浜掓枼閿?/span>
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(foo);
t.join();
return 0;
}

杩欎簺鍙槸C++绾跨▼鐨勪竴浜涘父瑙佺敤娉曪紝杩樻湁鍏朵粬鏇撮珮绾х殑鐢ㄦ硶锛屽绾跨▼闂寸殑閫氫俊銆佺嚎绋嬫睜绛夈€?/p>

扫码添加客服微信