これを使用して C++ でスレッドを作成したりstd::thread
、スレッド クラスをカスタマイズしてスレッドのライフ サイクルを管理したりできます。以下は、スレッド クラスをカスタマイズする方法を示す簡単な例です。
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
class MyThread {
public:
MyThread() {
m_running = false;
std::cout << "enter MyThread!\n";
}
virtual ~MyThread() {
std::cout << "enter ~MyThread!\n";
if (m_running) {
stop();
}
}
void start() {
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_running) {
m_thread = std::thread(&MyThread::run, this);
m_running = true;
}
}
void stop() {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_running) {
m_running = false;
m_thread.join();
}
}
protected:
virtual void run() {
while (m_running) {
// 线程执行的代码
std::cout << "Hello from MyThread!\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
private:
std::thread m_thread;
bool m_running;
std::mutex m_mutex;
};
class MyTask : public MyThread {
protected:
virtual void run() override {
// 重写线程执行的代码
std::cout << "Hello from MyTask!\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
int main() {
#if 1
MyThread thread;
thread.start();
// 执行一些操作
std::this_thread::sleep_for(std::chrono::seconds(3));
thread.stop();
///
MyTask task;
task.start();
// 执行一些操作
std::this_thread::sleep_for(std::chrono::seconds(3));
task.stop();
#else
MyThread thread;
MyTask task;
thread.start();
task.start();
// 执行一些操作
std::this_thread::sleep_for(std::chrono::seconds(3));
thread.stop();
task.stop();
#endif
return 0;
}
上記のコードでは、MyThread
という名前のスレッド クラスを定義します。このクラスには、スレッドの開始、スレッドの停止、スレッドの実行などのメソッドが含まれています。スレッドを開始するときに、スレッドの安全性を確保するためにミューテックスを取得し、スレッドが実行されていないときにのみスレッドを開始します。スレッドを停止すると、スレッドの安全性を確保するためにミューテックスも取得され、停止操作はスレッドの実行中にのみ実行されます。
さらに、MyThread
仮想関数を使用してrun
スレッドによって実行されるコードを表す場合、この関数はカスタム サブクラスに実装する必要があります。たとえば、上記のコードでは、 というサブクラスを定義し、スレッドの特定のタスクを実行するように関数をMyTask
書き換えます。run
なお、オブジェクトを破棄する際には、スレッドMyThread
が実行中かどうかを判断して、スレッドをstop
停止するメソッドを呼び出すかどうかを決定します。これにより、スレッドが破棄される前に確実に停止され、プログラムのクラッシュなどの問題が回避されます。
コンパイルして実行する
book@ubuntu:~/Desktop/c++_study$ g++ -o mythread mythread.cpp -lpthread
book@ubuntu:~/Desktop/c++_study$ ./mythread
enter MyThread!
Hello from MyThread!
Hello from MyThread!
Hello from MyThread!
enter MyThread!
Hello from MyTask!
enter ~MyThread!
enter ~MyThread!