帮我用c++写一个可以根据一个总任务数和设置线程数量并跑完任务数自动结束的带有启动,停止,暂停,恢复,安全快速线程类
时间: 2023-11-26 12:03:33 浏览: 70
C++实现的可以安全的暂停、继续、停止线程的线程类和Sample
5星 · 资源好评率100%
好的,代码如下:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
class ThreadSafeCounter {
public:
ThreadSafeCounter(int count) : count_(count) {}
void increment() {
unique_lock<mutex> lock(mutex_);
++count_;
cv_.notify_all();
}
void decrement() {
unique_lock<mutex> lock(mutex_);
--count_;
cv_.notify_all();
}
int get_count() const {
return count_;
}
void wait() {
unique_lock<mutex> lock(mutex_);
cv_.wait(lock, [this] { return count_ == 0; });
}
private:
mutable mutex mutex_;
condition_variable cv_;
int count_;
};
class ThreadController {
public:
ThreadController(int num_threads, int total_tasks) :
num_threads_(num_threads),
total_tasks_(total_tasks),
task_counter_(total_tasks) {}
void start() {
for (int i = 0; i < num_threads_; ++i) {
threads_.emplace_back([this] {
while (true) {
unique_lock<mutex> lock(mutex_);
cv_.wait(lock, [this] { return running_ || stop_requested_; });
if (stop_requested_) {
return;
}
if (task_counter_.get_count() <= 0) {
running_ = false;
stop_requested_ = true;
cv_.notify_all();
return;
}
task_counter_.decrement();
lock.unlock();
do_task();
lock.lock();
}
});
}
running_ = true;
}
void stop() {
unique_lock<mutex> lock(mutex_);
stop_requested_ = true;
cv_.notify_all();
for (auto& thread : threads_) {
thread.join();
}
threads_.clear();
running_ = false;
stop_requested_ = false;
task_counter_ = ThreadSafeCounter(total_tasks_);
}
void pause() {
unique_lock<mutex> lock(mutex_);
running_ = false;
}
void resume() {
unique_lock<mutex> lock(mutex_);
running_ = true;
cv_.notify_all();
}
bool is_running() const {
unique_lock<mutex> lock(mutex_);
return running_;
}
bool is_paused() const {
unique_lock<mutex> lock(mutex_);
return !running_ && !stop_requested_;
}
bool is_stopped() const {
unique_lock<mutex> lock(mutex_);
return stop_requested_;
}
private:
void do_task() {
// Replace this with actual task implementation
cout << "Task completed by thread " << this_thread::get_id() << endl;
this_thread::sleep_for(chrono::milliseconds(500));
}
int num_threads_;
int total_tasks_;
vector<thread> threads_;
ThreadSafeCounter task_counter_;
mutable mutex mutex_;
condition_variable cv_;
bool running_ = false;
bool stop_requested_ = false;
};
int main() {
ThreadController controller(4, 20);
controller.start();
this_thread::sleep_for(chrono::seconds(2));
controller.pause();
cout << "Paused!" << endl;
this_thread::sleep_for(chrono::seconds(2));
controller.resume();
cout << "Resumed!" << endl;
this_thread::sleep_for(chrono::seconds(2));
controller.stop();
cout << "Stopped!" << endl;
return 0;
}
```
这个类可以根据指定的线程数量启动多个线程,并让它们完成指定数量的任务。它支持启动、停止、暂停和恢复操作,可以安全、快速地处理线程。
阅读全文