c++实现一个类,继承thread,类内部实现一个线程任务
时间: 2024-01-22 12:21:28 浏览: 72
下面是一个简单的 C++ 类继承 thread,实现一个线程任务的例子:
```cpp
#include <iostream>
#include <thread>
using namespace std;
class MyThread : public thread {
public:
MyThread() {}
void run() {
cout << "Thread is running!" << endl;
}
};
int main() {
MyThread t;
t.run();
return 0;
}
```
在这个例子中,我们创建了一个名为 MyThread 的类,继承了 C++11 中的 thread 类。该类中的 run() 函数是我们要在线程中执行的任务。
在主函数中,我们创建了一个 MyThread 对象 t,并调用了它的 run() 函数。这将启动一个新的线程,并在该线程中执行 MyThread 类的 run() 函数。
需要注意的是,这里并没有显式地调用 C++11 中 thread 类的 start() 函数,因为在 MyThread 类的构造函数中已经隐式调用了 start() 函数。
相关问题
c++新建一个类,继承thread
在C++中,如果要新建一个类并继承自 `std::thread`,可以按照以下方式实现:
```c++
#include <iostream>
#include <thread>
class MyThread : public std::thread {
public:
// 构造函数
MyThread() : std::thread() {}
// 带参数的构造函数
template <typename... Args>
explicit MyThread(Args&&... args) : std::thread(std::forward<Args>(args)...) {}
// 重载运算符(),用于执行线程函数
virtual void operator()() {
std::cout << "MyThread is running!" << std::endl;
}
};
int main() {
MyThread t;
t.join();
return 0;
}
```
在上面的代码中,我们定义了一个名为 `MyThread` 的类,继承自 `std::thread`。然后我们重载了运算符 `()`,用于执行线程函数。在 `main` 函数中,我们实例化了一个 `MyThread` 对象 `t`,并调用了 `join` 函数等待线程执行完成。
c++11实现安全线程类
C++11提供了一些新的线程库,可以更方便地编写线程安全的代码。以下是一个简单的线程类实现,使用了C++11的std::thread和std::mutex来实现线程安全。
```c++
#include <thread>
#include <mutex>
class Thread {
public:
Thread() : m_thread(), m_running(false), m_mutex() {}
virtual ~Thread() {}
void start() {
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_running) {
m_running = true;
m_thread = std::thread(&Thread::run, this);
}
}
void stop() {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_running) {
m_running = false;
m_thread.join();
}
}
virtual void run() = 0;
private:
std::thread m_thread;
bool m_running;
std::mutex m_mutex;
};
```
在上面的代码中,我们创建了一个名为Thread的类,其中包含了一个std::thread和一个std::mutex来实现线程的启动和停止。
start()方法用于启动线程,它首先获取了一个std::lock_guard<std::mutex>类型的锁,以确保线程安全。然后检查线程是否已经运行,如果没有运行,则将m_running标志设置为true,并启动一个新的线程,该线程调用run()方法来执行实际的线程代码。
stop()方法用于停止线程,它也获取了一个std::lock_guard<std::mutex>类型的锁,以确保线程安全。然后检查线程是否正在运行,如果正在运行,则将m_running标志设置为false,并等待线程结束。
最后,我们定义了一个纯虚拟的run()方法,该方法必须由派生类实现,以提供实际的线程代码。
使用这个Thread类的示例代码如下:
```c++
#include <iostream>
class MyThread : public Thread {
public:
virtual void run() {
for (int i = 0; i < 10; ++i) {
std::cout << "MyThread: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
};
int main() {
MyThread thread;
thread.start();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
thread.stop();
return 0;
}
```
在上面的例子中,我们创建了一个名为MyThread的类,该类继承自Thread类,并实现了run()方法,以打印一些文本和等待一段时间。
然后我们在main()函数中创建了一个MyThread对象,并调用了start()方法来启动线程。然后我们等待1秒钟,然后调用stop()方法来停止线程。