在 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。