在Linux下,使用C++多线程和线程池可以有效地执行并发任务
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
class ThreadPool {
public:
ThreadPool(size_t num_threads);
~ThreadPool();
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;
private:
// 工作线程函数
void worker(size_t id);
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex task_queue_mutex;
std::condition_variable condition;
bool stop = false;
};
ThreadPool::ThreadPool(size_t num_threads) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back(&ThreadPool::worker, this, i);
}
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(task_queue_mutex);
stop = true;
}
condition.notify_all();
for (auto& worker : workers) {
worker.join();
}
}
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> result = task->get_future();
{
std::unique_lock<std::mutex> lock(task_queue_mutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return result;
}
void ThreadPool::worker(size_t id) {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(task_queue_mutex);
condition.wait(lock, [this]() { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
}
int main() {
ThreadPool pool(4);
auto result1 = pool.enqueue([](int a, int b) { return a + b; }, 5, 3);
std::cout << "Result 1: " << result1.get() << std::endl;
auto result2 = pool.enqueue([](int a, int b) { return a * b; }, 4, 6);
std::cout << "Result 2: " << result2.get() << std::endl;
return 0;
}
这个简单的线程池实现可以处理并发任务,并在Linux下使用C++多线程进行任务调度。当然,你可以根据实际需求对这个实现进行扩展和优化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。