您好,登錄后才能下訂單哦!
在Linux下,使用C++多線程和線程池可以有效地執(zhí)行并發(fā)任務(wù)
#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:
// 工作線程函數(shù)
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;
}
這個簡單的線程池實(shí)現(xiàn)可以處理并發(fā)任務(wù),并在Linux下使用C++多線程進(jìn)行任務(wù)調(diào)度。當(dāng)然,你可以根據(jù)實(shí)際需求對這個實(shí)現(xiàn)進(jìn)行擴(kuò)展和優(yōu)化。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。