网站建设的数据导入导出,wordpress 转繁体,上饶网站建设多少钱,用python自动写wordpress一、线程池设计
概念#xff1a;线程池是一种管理线程资源的机制#xff0c;预先创建一定数量的线程#xff0c;当有任务提交时#xff0c;从线程池中获取线程执行任务#xff0c;任务完成后线程不会销毁而是返回线程池等待下一个任务。核心组件 线程管理器#xff1a;负…一、线程池设计
概念线程池是一种管理线程资源的机制预先创建一定数量的线程当有任务提交时从线程池中获取线程执行任务任务完成后线程不会销毁而是返回线程池等待下一个任务。核心组件 线程管理器负责创建、销毁和管理线程。任务队列存储待执行的任务。任务接口定义任务的执行方式。 C实现示例
#include vector
#include queue
#include memory
#include thread
#include mutex
#include condition_variable
#include future
#include functional
#include stdexceptclass ThreadPool {
public:ThreadPool(size_t threads);templateclass F, class... Argsauto enqueue(F f, Args... args) - std::futuretypename std::result_ofF(Args...)::type;~ThreadPool();
private:// 工作线程集合std::vectorstd::thread workers;// 任务队列std::queuestd::functionvoid() tasks;// 同步相关std::mutex queue_mutex;std::condition_variable condition;bool stop;
};// 构造函数创建指定数量的工作线程
inline ThreadPool::ThreadPool(size_t threads): stop(false) {for(size_t i 0; i threads; i) {workers.emplace_back([this] {while(true) {std::functionvoid() task;{std::unique_lockstd::mutex lock(this-queue_mutex);this-condition.wait(lock, [this] { return this-stop || !this-tasks.empty(); });if(this-stop this-tasks.empty())return;task std::move(this-tasks.front());this-tasks.pop();}task();}});}
}// 添加新的任务到线程池
templateclass F, class... Args
auto ThreadPool::enqueue(F f, Args... args) - std::futuretypename std::result_ofF(Args...)::type {using return_type typename std::result_ofF(Args...)::type;auto task std::make_sharedstd::packaged_taskreturn_type()(std::bind(std::forwardF(f), std::forwardArgs(args)...));std::futurereturn_type res task-get_future();{std::unique_lockstd::mutex lock(queue_mutex);// 不允许向已停止的线程池添加任务if(stop)throw std::runtime_error(enqueue on stopped ThreadPool);tasks.emplace([task]() { (*task)(); });}condition.notify_one();return res;
}// 析构函数销毁线程池
inline ThreadPool::~ThreadPool() {{std::unique_lockstd::mutex lock(queue_mutex);stop true;}condition.notify_all();for(std::thread worker : workers) {worker.join();}
}使用示例
// 创建一个包含4个线程的线程池
ThreadPool pool(4);// 向线程池提交任务
std::vectorstd::futureint results;for(int i 0; i 8; i) {results.emplace_back(pool.enqueue([i] {std::cout hello i std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));std::cout world i std::endl;return i*i;}));
}// 等待所有任务完成并获取结果
for(auto result : results)std::cout result.get() ;
std::cout std::endl;二、锁优化
读写锁
概念读写锁允许多个线程同时读取共享资源但在写操作时会独占资源实现“多读单写”的机制。C实现
#include shared_mutex // C17引入
#include mutex
#include map
#include stringclass ThreadSafeHashMap {
private:mutable std::shared_mutex mtx;std::mapstd::string, int data;public:// 读操作允许多个线程同时进行int get(const std::string key) const {std::shared_lockstd::shared_mutex lock(mtx);auto it data.find(key);return it ! data.end() ? it-second : -1;}// 写操作独占锁void set(const std::string key, int value) {std::unique_lockstd::shared_mutex lock(mtx);data[key] value;}
};适用场景适用于读多写少的场景如缓存系统。
无锁队列
概念无锁队列使用原子操作替代传统的锁机制避免线程阻塞提高并发性能。C实现基于CAS操作
#include atomic
#include memorytemplatetypename T
class LockFreeQueue {
private:struct Node {T data;std::atomicNode* next;Node(const T value) : data(value), next(nullptr) {}};std::atomicNode* head;std::atomicNode* tail;public:LockFreeQueue() : head(nullptr), tail(nullptr) {}void enqueue(const T value) {Node* newNode new Node(value);Node* oldTail tail.load();while (!tail.compare_exchange_weak(oldTail, newNode)) {}if (oldTail) {oldTail-next newNode;} else {head newNode;}}bool dequeue(T value) {Node* oldHead head.load();while (oldHead) {Node* next oldHead-next.load();if (head.compare_exchange_weak(oldHead, next)) {value oldHead-data;delete oldHead;return true;}}return false;}~LockFreeQueue() {T value;while (dequeue(value)) {}}
};适用场景适用于高性能要求的生产者-消费者模型。
性能对比与选择策略
技术优点缺点适用场景传统互斥锁实现简单适用广泛线程阻塞上下文切换开销大竞争不激烈的场景读写锁提高读并发性能实现复杂写操作可能饥饿读多写少的场景无锁队列无阻塞高性能实现复杂调试困难高性能要求的队列操作
在实际应用中需要根据具体场景选择合适的并发技术必要时可以组合使用多种技术以达到最佳性能。