C++ スレッドの用途

C++のthreadライブラリにはスレッドの作成と管理を行う多数の方法があります。以下には一般的な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. ラムダ式でスレッドを作成する:
#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++スレッドで一般的に使われるのはこれらのみで、スレッド間の通信、スレッドプールなど、他にもより高度な使い方があります。

bannerAds