您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。