首页 > 编程语言 > 详细

muduo源码分析之Thread线程

时间:2021-06-09 09:23:31      阅读:18      评论:0      收藏:0      [点我收藏+]

相关文件

muduo/base/Thread.h//线程类
muduo/base/Thread.cc

muduo/base/currentThread.h //线程真实pid,即tid
muduo/base/cuurentThread.cc

作用

开启一个线程,执行用户函数。

使用

#include <muduo/base/Thread.h>
#include <boost/bind.hpp>
#include <unistd.h>
#include <iostream>
using namespace std;

using namespace muduo;

class Foo
{
public:
  Foo(int count) : count_(count)
  {
  }

  void MemberFun()
  {
    while (count_--)
    {
      cout<<"this is a test ..."<<endl;
      sleep(1);
    }
  }

  void MemberFun2(int x)
  {
    while (count_--)
    {
      cout<<"x="<<x<<" this is a test2 ..."<<endl;
      sleep(1);
    }
  }

  int count_;
};

void ThreadFunc()
{
  cout<<"ThreadFunc ..."<<endl;
}

void ThreadFunc2(int count)
{
  while (count--)
  {
    cout<<"ThreadFunc2 ..."<<endl;
    sleep(1);
  }
}


int main(void)
{
  Thread t1(ThreadFunc); //无参函数
  Thread t2(boost::bind(ThreadFunc2, 3));//有参函数
  Foo foo(3);
  Thread t3(boost::bind(&Foo::MemberFun, &foo));//无参类方法
  Foo foo2(3);
  Thread t4(boost::bind(&Foo::MemberFun2, &foo2, 1000));//有参类方法

  t1.start(); //开始执行
  t2.start();
  t3.start();
  t4.start();

  t1.join(); //阻塞等待线程结束
  t2.join();
  t3.join();
  t4.join();

  return 0;
}

Thread源码分析

muduo源码分析之Thread线程

原文:https://www.cnblogs.com/Lj-ming/p/14865123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!