您好,登錄后才能下訂單哦!
在 Linux 中使用 C++ 編寫可重用的多線程組件需要遵循以下步驟:
<iostream>
、<thread>
、<mutex>
和 <vector>
。#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
std::mutex
)。定義一個全局互斥鎖對象,以便在多個線程之間共享。std::mutex mtx;
void execute_tasks(const std::vector<std::function<void()>>& tasks) {
for (const auto& task : tasks) {
std::unique_lock<std::mutex> lock(mtx);
task();
lock.unlock();
}
}
class ThreadPool {
public:
ThreadPool(size_t num_threads) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back(&ThreadPool::worker_thread, this);
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mtx);
stop = true;
}
cv.notify_all();
for (auto& worker : workers) {
if (worker.joinable()) {
worker.join();
}
}
}
template <typename F, typename... Args>
void enqueue(F&& task, Args&&... args) {
{
std::unique_lock<std::mutex> lock(mtx);
tasks.emplace_back(std::bind(std::forward<F>(task), std::forward<Args>(args)...));
}
cv.notify_one();
}
private:
void worker_thread() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.erase(tasks.begin());
}
task();
}
}
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex mtx;
std::condition_variable cv;
bool stop = false;
};
int main() {
ThreadPool pool(4);
std::vector<std::function<void()>> tasks = {
[] { std::cout << "Task 1 is running in thread " << std::this_thread::get_id() << std::endl; },
[] { std::cout << "Task 2 is running in thread " << std::this_thread::get_id() << std::endl; },
[] { std::cout << "Task 3 is running in thread " << std::this_thread::get_id() << std::endl; },
};
for (const auto& task : tasks) {
pool.enqueue(task);
}
return 0;
}
這個例子展示了如何在 Linux 中使用 C++ 編寫可重用的多線程組件。你可以根據需要擴展這個類,以支持更多的功能和配置選項。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。