muduo网络库源码学习————线程类
muduo库里面的线程类是使用基于对象的编程思想,源码目录为muduo/base,如下所示:
线程类头文件:
// 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)
//线程类
#ifndef MUDUO_BASE_THREAD_H
#define MUDUO_BASE_THREAD_H
#include <muduo/base/Atomic.h>
#include <muduo/base/Types.h>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <pthread.h>
//线程类头文件
namespace muduo
{
class Thread : boost::noncopyable
{
public:
typedef boost::function<void ()> ThreadFunc;//函数适配接收的函数
//线程构造函数,参数为回调函数和线程名称
explicit Thread(const ThreadFunc&, const string& name = string());//名称默认值为空的字符串类
//线程析构函数
~Thread();
void start();//启动线程
int join(); // return pthread_join()
bool started() const { return started_; }//线程是否已经启动
// pthread_t pthreadId() const { return pthreadId_; }
pid_t tid() const { return tid_; }//线程的真实pid
const string& name() const { return name_; }//线程的名称
static int numCreated() { return numCreated_.get(); }//已经启动的线程个数
private:
static void* startThread(void* thread);//现成的入口函数,调用runInThread函数
void runInThread();//调用回调函数func_
bool started_;//线程是否已经启动
pthread_t pthreadId_;//线程的pthread_t
pid_t tid_;//线程真实的 pid
ThreadFunc func_;//线程的回调函数
string name_;//线程的名称
static AtomicInt32 numCreated_;//已经创建的线程的个数,每当创建一个线程,该值就加一(原子整数类)
};
}
#endif
线程类的实现文件:
// 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/base/Thread.h>
#include <muduo/base/CurrentThread.h>
#include <muduo/base/Exception.h>
//#include <muduo/base/Logging.h>
//暂时不用日志文件,先注释掉
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <linux/unistd.h>
namespace muduo
{
namespace CurrentThread
{//__thread两个下划线是gcc 内置的线程局部存储设施
//每个线程各有一个,并不会去共享他
//缓存获取tid是为了提高获取tid的效率
__thread int t_cachedTid = 0;//线程真实pid的缓存,如果每次都用系统调用去获取pid,效率会低
__thread char t_tidString[32];//tid的字符串表示形式
__thread const char* t_threadName = "unknown";//线程的名称
const bool sameType = boost::is_same<int, pid_t>::value;//如果是相同类型,返回true
BOOST_STATIC_ASSERT(sameType);//编译时断言
}
namespace detail
{
pid_t gettid()//通过系统调用SYS_gettid获得tid
{
return static_cast<pid_t>(::syscall(SYS_gettid));//类型转化为pid_t
}
void afterFork()//子进程调用的
{
muduo::CurrentThread::t_cachedTid = 0;//当前线程pid赋值0
muduo::CurrentThread::t_threadName = "main";//名称赋值name
CurrentThread::tid();//进行缓存
// no need to call pthread_atfork(NULL, NULL, &afterFork);
}
class ThreadNameInitializer
{
public:
ThreadNameInitializer()//构造函数
{
muduo::CurrentThread::t_threadName = "main";//线程名称赋为main,即为主线程名称
CurrentThread::tid();//缓存当前线程的pid
//#include <pthread.h>
//int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void));
//调用fork时,内部创建子进程前在父进程中会调用prepare,
//内部创建子进程成功后,父进程会调用parent ,子进程会调用child
pthread_atfork(NULL, NULL, &afterFork);//如果使用fork函数,那么子进程会调用邋afterFork
}
};
ThreadNameInitializer init;
}
}
using namespace muduo;
void CurrentThread::cacheTid()
{
if (t_cachedTid == 0)
{
t_cachedTid = detail::gettid();//调用gettid函数获得tid
int n = snprintf(t_tidString, sizeof t_tidString, "%5d ", t_cachedTid);//将tid格式化保存在t_tidString中
assert(n == 6);//断言长度是6,5d后面还有一个空格,所以是6
(void) n;//这一句主要是预防n没有使用从而产生警告
}
}
bool CurrentThread::isMainThread()
{
return tid() == ::getpid();//查看tid是否等于当前进程id
}
AtomicInt32 Thread::numCreated_;
//构造函数,初始化
Thread::Thread(const ThreadFunc& func, const string& n) : started_(false), pthreadId_(0),tid_(0),func_(func),name_(n)
{
numCreated_.increment();//创建的线程的个数加一,为原子性操作
}
Thread::~Thread()
{
// no join
}
void Thread::start()
{
assert(!started_);
started_ = true;
//创建线程,startThread为线程的入口函数
errno = pthread_create(&pthreadId_, NULL, &startThread, this);
if (errno != 0)
{//日志
// LOG_SYSFATAL << "Failed in pthread_create";
}
}
int Thread::join()
{
assert(started_);
return pthread_join(pthreadId_, NULL);
}
//线程的入口函数
void* Thread::startThread(void* obj)
{//this指针传到obj
Thread* thread = static_cast<Thread*>(obj);//转化为线程基类的指针
thread->runInThread();//调用线程函数runInThread
return NULL;
}
//被线程的入口函数调用
void Thread::runInThread()
{
tid_ = CurrentThread::tid();//获取线程的tid
muduo::CurrentThread::t_threadName = name_.c_str();//缓存该线程的名称
try
{
func_();//调用回调函数
muduo::CurrentThread::t_threadName = "finished";
}
catch (const Exception& ex)//异常捕捉
{
muduo::CurrentThread::t_threadName = "crashed";
fprintf(stderr, "exception caught in Thread %s\n", name_.c_str());
fprintf(stderr, "reason: %s\n", ex.what());
fprintf(stderr, "stack trace: %s\n", ex.stackTrace());
abort();
}
catch (const std::exception& ex)
{
muduo::CurrentThread::t_threadName = "crashed";
fprintf(stderr, "exception caught in Thread %s\n", name_.c_str());
fprintf(stderr, "reason: %s\n", ex.what());
abort();
}
catch (...)
{
muduo::CurrentThread::t_threadName = "crashed";
fprintf(stderr, "unknown exception caught in Thread %s\n", name_.c_str());
throw; // rethrow
}
}
CurrentThread头文件
// 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)
#ifndef MUDUO_BASE_CURRENTTHREAD_H
#define MUDUO_BASE_CURRENTTHREAD_H
namespace muduo
{//CurrentThread的名称空间
namespace CurrentThread
{
// internal
extern __thread int t_cachedTid;
extern __thread char t_tidString[32];
extern __thread const char* t_threadName;
void cacheTid();
inline int tid()
{
if (t_cachedTid == 0)//还没有缓存过
{//t_cachedTid初值 是0
cacheTid();//进行缓存
}
return t_cachedTid;//返回缓存的tid
}
inline const char* tidString() // for logging
{
return t_tidString;//返回tid的字符串表示形式
}
inline const char* name()
{
return t_threadName;//返回线程名称
}
bool isMainThread();//是否是主线程
}
}
#endif
测试代码位于muduo/base/tests
//线程测试程序
#include <muduo/base/Thread.h>
#include <muduo/base/CurrentThread.h>
#include <string>
#include <boost/bind.hpp>
#include <stdio.h>
void threadFunc()
{
printf("tid=%d\n", muduo::CurrentThread::tid());
}
void threadFunc2(int x)
{
printf("tid=%d, x=%d\n", muduo::CurrentThread::tid(), x);
}
class Foo
{
public:
explicit Foo(double x) : x_(x)
{
}
void memberFunc()
{
printf("tid=%d, Foo::x_=%f\n", muduo::CurrentThread::tid(), x_);
}
void memberFunc2(const std::string& text)
{
printf("tid=%d, Foo::x_=%f, text=%s\n", muduo::CurrentThread::tid(), x_, text.c_str());
}
private:
double x_;
};
int main()
{//获取当前线程的pid(进程id 线程pid)
printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid());
//创建一个线程对象,传递一个函数
muduo::Thread t1(threadFunc);
t1.start();//启动线程
t1.join();
//threadFunc2带了一个参数,用boost::bind函数传递进去,最后是线程的名称,可以不传
muduo::Thread t2(boost::bind(threadFunc2, 42), "thread for free function with argument");
t2.start();
t2.join();
//创建一个对象
Foo foo(87.53);
//创建第三个线程(成员函数的话一定要用&)
muduo::Thread t3(boost::bind(&Foo::memberFunc, &foo), "thread for member function without argument");
t3.start();
t3.join();
//创建第四个线程,这里传进去的函数是带参数的
muduo::Thread t4(boost::bind(&Foo::memberFunc2, boost::ref(foo), std::string("Shuo Chen")));
t4.start();
t4.join();
//打印最后创建的线程总数
printf("number of created threads %d\n", muduo::Thread::numCreated());
}
单独编译后运行结果如下:
muduo网络库源码学习————线程类的更多相关文章
- muduo网络库源码学习————线程本地单例类封装
muduo库中线程本地单例类封装代码是ThreadLocalSingleton.h 如下所示: //线程本地单例类封装 // Use of this source code is governed b ...
- muduo网络库源码学习————线程池实现
muduo库里面的线程池是固定线程池,即创建的线程池里面的线程个数是一定的,不是动态的.线程池里面一般要包含线程队列还有任务队列,外部程序将任务存放到线程池的任务队列中,线程池中的线程队列执行任务,也 ...
- muduo网络库源码学习————线程特定数据
muduo库线程特定数据源码文件为ThreadLocal.h //线程本地存储 // Use of this source code is governed by a BSD-style licens ...
- muduo网络库源码学习————日志类封装
muduo库里面的日志使方法如下 这里定义了一个宏 #define LOG_INFO if (muduo::Logger::logLevel() <= muduo::Logger::INFO) ...
- muduo网络库源码学习————线程安全
线程安全使用单例模式,保证了每次只创建单个对象,代码如下: Singleton.h // Use of this source code is governed by a BSD-style lice ...
- muduo网络库源码学习————Exception类
Exception类是为异常捕获而设计,可以获得异常的信息以及栈的回溯信息 (原来的代码没有demangle成员函数,输出的格式比较难看,加了demangle成员函数,利用demangle成员函数可以 ...
- muduo网络库源码学习————Timestamp.cc
今天开始学习陈硕先生的muduo网络库,moduo网络库得到很多好评,陈硕先生自己也说核心代码不超过5000行,所以我觉得有必要拿过来好好学习下,学习的时候在源码上面添加一些自己的注释,方便日后理解, ...
- muduo网络库源码学习————互斥锁
muduo源码的互斥锁源码位于muduo/base,Mutex.h,进行了两个类的封装,在实际的使用中更常使用MutexLockGuard类,因为该类可以在析构函数中自动解锁,避免了某些情况忘记解锁. ...
- muduo网络库源码学习————日志滚动
muduo库里面的实现日志滚动有两种条件,一种是日志文件大小达到预设值,另一种是时间到达超过当天.滚动日志类的文件是LogFile.cc ,LogFile.h 代码如下: LogFile.cc #in ...
随机推荐
- Linux bash篇(三 数据流重定向)
1> 以覆盖的方式将正确的数据输出到文件或设备上 1>> 以追加的方式将正确的数据输出到文件或设备上 2> 以覆盖的方式将错误的数据输 ...
- 36 Thread 多线程
/* * 多线程的实现方式: * 方式1:一种方法是将类声明为 Thread 的子类.该子类应重写 Thread 类的 run 方法.接下来可以分配并启动该子类的实例 * * Thread * Str ...
- MySQL REPLACE INTO 的使用
前段时间写游戏合服工具时出现过一个问题,源DB和目标DB角色表中主键全部都不相同,从源DB取出玩家数据再使用 replace into 写入目标DB中,结果总有几条数据插入时会导致目标DB中原有的角色 ...
- HBase协处理器加载的三种方式
本文主要给大家罗列了HBase协处理器加载的三种方式:Shell加载(动态).Api加载(动态).配置文件加载(静态).其中静态加载方式需要重启HBase. 我们假设我们已经有一个现成的需要加载的协处 ...
- 理解class.forName() ---使用jdbc方式链接数据库时会经常看到这句代码
目录(?)[-] 官方文档 类装载 两种装载方法的区别 不同的类装载器 是否实例化类 在jdbc链接数据库中的应用 资源 原文地址:http://yanwushu.sinaapp.com/clas ...
- xxx 表 is marked as crashed and last (automatic?) repair 解决办法
如上图出现 xxx 表 is marked xxxx 的问题 运维那说是因为数据库非正常停掉 时 刚好有数据正在写入 数据库 导致的问题,这个没多大影响,需要 执行命令修复数据库,至于命令是什么? ...
- stand up meeting 12/8/2015
part 组员 今日工作 工作耗时/h 明日计划 工作耗时/h UI 冯晓云 -------------- -- ----------- -- PDF Reader 朱玉影 ...
- js的localStorage基础认识
新建a.html文件: <!DOCTYPE html> <html> <body> <div id="result"></di ...
- Prometheus监控 Redis & Redis Cluster 说明
说明 在前面的Prometheus + Grafana 部署说明之「安装」文章里,大致介绍说明了Prometheus和Grafana的一些安装使用,现在开始如何始部署Prometheus+Grafan ...
- [linux][MongoDB] mongodb学习(一):MongoDB安装、管理工具、
参考原文:http://www.cnblogs.com/kaituorensheng/p/5118226.html linux安装完美实现! 1. mongoDB安装.启动.关闭 1.1 下载安装包 ...