30muduo_net库源码分析(六)

本文介绍muduo库中的IO线程模型,包括EventLoopThread类的实现细节,展示了如何创建和启动IO线程,并通过示例代码说明了如何在IO线程上执行任务。

1.EventThread

(1)任何一个线程,只要创建并运行了EventLoop,都称之为IO线程
(2)IO线程不一定是主线程
(3)muduo并发模型one loop per thread + threadpool
(4)为了方便今后使用,定义了EventLoopThread类,该类封装了IO线程
(5)EventLoopThread创建了一个线程
(6)在线程函数中创建了一个EvenLoop对象并调用EventLoop::loop

2.代码

1.EventLoopThread.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.

#ifndef MUDUO_NET_EVENTLOOPTHREAD_H
#define MUDUO_NET_EVENTLOOPTHREAD_H

#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/Thread.h>

#include <boost/noncopyable.hpp>

namespace muduo
{
namespace net
{

class EventLoop;

class EventLoopThread : boost::noncopyable
{
 public:
  typedef boost::function<void(EventLoop*)> ThreadInitCallback;

  EventLoopThread(const ThreadInitCallback& cb = ThreadInitCallback());
  ~EventLoopThread();
  EventLoop* startLoop();	// 启动线程,该线程就成为了IO线程

 private:
  void threadFunc();		// 线程函数

  EventLoop* loop_;			// loop_指针指向一个EventLoop对象
  bool exiting_;
  Thread thread_;
  MutexLock mutex_;
  Condition cond_;
  ThreadInitCallback callback_;		// 回调函数在EventLoop::loop事件循环之前被调用
};

}
}

#endif  // MUDUO_NET_EVENTLOOPTHREAD_H


2.EventLoopthread.cc

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/EventLoopThread.h>

#include <muduo/net/EventLoop.h>

#include <boost/bind.hpp>

using namespace muduo;
using namespace muduo::net;


EventLoopThread::EventLoopThread(const ThreadInitCallback& cb)
  : loop_(NULL),
    exiting_(false),
    thread_(boost::bind(&EventLoopThread::threadFunc, this)),
    mutex_(),
    cond_(mutex_),
    callback_(cb)
{
}

EventLoopThread::~EventLoopThread()
{
  exiting_ = true;
  loop_->quit();		// 退出IO线程,让IO线程的loop循环退出,从而退出了IO线程
  thread_.join();
}

EventLoop* EventLoopThread::startLoop()
{
  assert(!thread_.started());
  thread_.start();

  {
    MutexLockGuard lock(mutex_);
    while (loop_ == NULL)
    {
      cond_.wait();
    }
  }

  return loop_;
}

void EventLoopThread::threadFunc()
{
  EventLoop loop;

  if (callback_)
  {
    callback_(&loop);
  }

  {
    MutexLockGuard lock(mutex_);
    // loop_指针指向了一个栈上的对象,threadFunc函数退出之后,这个指针就失效了
    // threadFunc函数退出,就意味着线程退出了,EventLoopThread对象也就没有存在的价值了。
    // 因而不会有什么大的问题
    loop_ = &loop;
    cond_.notify();
  }

  loop.loop();
  //assert(exiting_);
}


3.Reactor_test06.cc

#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>

#include <stdio.h>

using namespace muduo;
using namespace muduo::net;

void runInThread()
{
  printf("runInThread(): pid = %d, tid = %d\n",
         getpid(), CurrentThread::tid());
}

int main()
{
  printf("main(): pid = %d, tid = %d\n",
         getpid(), CurrentThread::tid());

  EventLoopThread loopThread;
  EventLoop* loop = loopThread.startLoop();
  // 异步调用runInThread,即将runInThread添加到loop对象所在IO线程,让该IO线程执行
  loop->runInLoop(runInThread);
  sleep(1);
  // runAfter内部也调用了runInLoop,所以这里也是异步调用
  loop->runAfter(2, runInThread);
  sleep(3);
  loop->quit();

  printf("exit main().\n");
}


### muduo网络源码解读与分析 muduo网络是由陈硕(Chen Shuo)开发的一个高性能的C++网络,主要用于构建跨平台的网络服务应用。它基于Linux平台,充分利用了现代C++特性以及高效的系统调用机制(如`epoll`),提供了线程池、事件循环、TCP连接管理等功能。以下是关于muduo网络源码的解读和分析: #### 1. 设计理念 muduo的设计目标是提供一个简单、高效且易于扩展的网络编程框架。它的设计遵循了现代C++的最佳实践,例如RAII(Resource Acquisition Is Initialization)[^1],避免了资源泄漏问题,并通过智能指针管理对象生命周期。此外,muduo还强调了代码的可读性和可维护性。 #### 2. 核心组件 muduo的核心组件包括以下几个部分: - **EventLoop**:事件循环模块,负责监听和分发事件。 - **Channel**:封装了文件描述符(file descriptor)及其相关的事件。 - **Poller**:具体实现事件轮询功能,基于`epoll`或其他类似的机制。 - **TcpConnection**:表示一个TCP连接,包含读写缓冲区、状态机等。 - **TcpServer**:用于创建和管理多个TCP连接。 - **Buffer**:高效的数据缓冲区,支持零拷贝操作。 #### 3. 源码结构 muduo的源码结构清晰,按照功能模块进行了划分。以下是一些主要目录及其作用: - `base/`:包含通用的基础工具类,如`Logging`、`Thread`、`Timestamp`等。 - `net/`:核心网络的实现,包括`EventLoop`、`TcpServer`、`TcpConnection`等。 - `examples/`:一些示例程序,展示了如何使用muduo构建实际应用。 - `tests/`:单元测试代码,验证的功能是否正确。 #### 4. 关键技术点 - **Reactor模式**:muduo采用了经典的Reactor模式来处理I/O事件,使得单线程可以高效地管理大量连接[^3]。 - **非阻塞I/O**:通过`epoll`实现高效的非阻塞I/O操作,避免了传统阻塞模型的性能瓶颈。 - **智能指针**:广泛使用`std::shared_ptr`和`std::unique_ptr`来管理动态分配的对象,确保资源的安全释放。 - **线程安全**:在多线程环境下,muduo通过锁机制或无锁队列保证数据的一致性。 #### 5. 学习资源 对于希望深入理解muduo网络的开发者,以下资源可能会有所帮助: - **官方文档**:虽然muduo没有详细的官方文档,但其源码本身非常清晰,适合阅读和学习。 - **书籍推荐**:W. Richard Stevens的《UNIX网络编程》系列是学习网络编程的经典教材,可以帮助理解muduo的设计思想[^2]。 - **社区讨论**:GitHub上有很多关于muduo的讨论和案例分析,可以作为参考。 - **博客文章**:一些开发者撰写了关于muduo源码的详细解读文章,可以通过搜索引擎查找。 ```python # 示例代码:简单的TcpServer使用 from muduo.net import TcpServer, InetAddress, EventLoop def on_connection(conn): if conn.is_connected(): print("New connection") else: print("Connection closed") def on_message(conn, buf, timestamp): print(f"Received: {buf}") loop = EventLoop() server = TcpServer(loop, InetAddress(9981), "TestServer") server.set_connection_callback(on_connection) server.set_message_callback(on_message) server.start() loop.loop() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值