安全队列
#include <thread>
#include <iostream>
#include <atomic>
#include <functional>
#include <vector>
#include "tsafe_queue.h"
using namespace std;
class join_t {
vector<thread>& threads;
public:
explicit join_t(vector<thread>& ts):threads(ts)
{}
~join_t() {
for (int i = 0; i < threads.size(); i++) {
if (threads[i].joinable())
threads[i].join();
}
}
};
class t_pool {
atomic_bool done;
tsafe_queue<function<void()>> works;
vector<thread> threads;
join_t joiner;
void worker_thread() {
while (!done) {
function<void()> task;
if (works.try_pop(task)) {
task();
}
else {
this_thread::yield();
}
}
}
public:
t_pool() :done(false), joiner(threads) {
unsigned const max_t = thread::hardware_concurrency() - 2;
try {
for (unsigned i = 0; i < max_t; i++) {
threads.push_back(
std::thread(&t_pool::worker_thread, this));
}
}
catch (...) {
done = true;
throw;
}
}
~t_pool() {
done = false;
}
template<typename F_T>
void submit(F_T f) {
works.push(function<void()>(f));
}
};
启动线程池以后,每个线程都在等待分配任务,都会去等待队列中取出任务。 简单测试一下。
int main()
{
t_pool p;
for (int i = 0; i < 1000; i++) {
p.submit([i]() {
cout << i * i<<endl;
});
}
return 0;
}
|