Chrome的线程体系

Chrome中的线程结构

网上已经有网友duguguiyu针对Chrome的线程体系做了很专业的描述了,应该说从原理上已经很完整了。本文主要在网友的基础上从代码实现的角度上进行一些补充和分析。
提到线程,我想大家关注的无非几点:线程的消息循环机制、多线程同步机制,线程间通信机制。
本文也是从大家关注的几点来重点描述。
在Chrome的代码中,与线程相关的文件主要在/base/base.vcproj中。
主要包含了以下相关文件:
task.h    线程执行的任何任务都是以task对象方式传递,有不同类型的task。
message_pump.h
message_pump_default.h
message_pump_default.cc
message_pump_win.h
message_pump_win.cc    消息泵类,消息调度,分发处理。
message_loop.h
message_loop.cc    消息循环机制,基本上每一个线程都有自己的消息循环,接收来自其他线程、UI甚至系统的消息。
thread.h
thread.cc     线程虚类类。Thread类在操作系统上层做了抽象,本身与平台无关
platform_thread.h
platform_thread_win.cc    Windows平台下线程的相关方法。在Windows平台下是CreateThread方法。
thread_local.h
thread_local.cc
thread_local_storage.h
thread_local_storage_win.cc    线程本地存储机制的实现(TLS)

其他还有一些辅助类,可以不用太关注,比如智能指针、一些简单的工具类等。我们重点分析上述的代码。


总体来说,Chrome的线程实现,主要运用了Command、Bridge和Observer三种模式。

线程类(Thread)的结构和简单流程

我们观看一下Thread.h中对Thread的定义

  1. //线程的抽象类
  2. // PlatformThread是底层的线程辅助类,实现不同平台下的真正的线程实现。
  3. // PlatformThread: Delegate,代理接口类,包含了ThreadMain函数。
  4. // Thread的子类实现,执行由PlatformThread传递到线程的回调函数中
  5. class Thread : PlatformThread::Delegate {
  6.  public:
  7.   struct Options {
  8.     //线程消息循环类型有三种,Default(普通的后台线程),UI,IO线程
  9.     //不同线程消息循环处理消息的方式有一些差异。
  10.     MessageLoop::Type message_loop_type;
  11.     //制定线程堆栈大小
  12.     size_t stack_size;
  13.     Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), stack_size(0) {}
  14.     Options(MessageLoop::Type type, size_t size)
  15.         : message_loop_type(type), stack_size(size) {}
  16.   };
  17.   explicit Thread(const char *name);
  18.  
  19.   virtual ~Thread();
  20.  
  21.   bool Start();
  22.  
  23.   bool StartWithOptions(const Options& options);
  24.  
  25.   void Stop();
  26.   
  27.   void StopSoon();
  28.  
  29.   //获取消息循环实例,每一个线程的核心消息循环所在
  30.   MessageLoop* message_loop() const { return message_loop_; }
  31.  
  32.   const std::string &thread_name() { return name_; }
  33.  
  34.   PlatformThreadHandle thread_handle() { return thread_; }
  35.  
  36.   PlatformThreadId thread_id() const { return thread_id_; }
  37.  
  38.   bool IsRunning() const { return thread_id_ != 0; }
  39.  
  40.  protected
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值