🌷🌷🌷🌷① 使用多线程处理网络连接
🌷🌷🌷🌷② 使用多线程处理网络请求
🌷🌷🌷🌷③ 使用多线程处理网络响应
🌷🌷🌷🌷④ 避免数据竞争和锁的协调
① 使用多线程处理网络连接
在网络编程中,常常需要创建多个套接字来处理多个连接。如果每个连接都使用一个线程来处理,那么线程数将会非常庞大,会造成系统资源的浪费。因此,可以使用线程池来处理多个连接。
下面是一个使用线程池处理网络连接的代码示例:
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(int thread_num) : stop(false) {
for (int i = 0; i < thread_num; ++i) {
threads.emplace_back(std::thread(&ThreadPool::worker, this));
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (auto &thread : threads) {
thread.join();
}
}
template<class F, class... Args>
auto 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> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
void worker() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(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);
// 接受连接并处理请求
while (true) {
int client_socket = accept(server_socket, nullptr, nullptr);
pool.enqueue(process_request, client_socket);
}
return 0;
}
以上代码使用了一个线程池来处理多个连接。线程池中包含了多个线程,每个线程会从任务队列中取出一个任务进行处理。当任务队列为空时,线程会等待新的任务加入。通过这种方式,我们可以利用有限的线程资源,处理大量的连接。