基于ptlib实现thread demo示例

本文主要写基于ptlib写一个使用线程的demo示例,可以实际运行起来

1. demo编译:

        g++ thread.cxx -lpt_s -lpthread -lresolv -ldl -L ./lib  -I./include -o testThread

注意:

  1. 创建线程后,需要调用Resume()函数来执行线程(可以在构造函数或者start方法调用)
  2. 使用ptlib的线程,必须先要有一个PProcess的实例,表示一个应用程序,所化PProcess再创建线程,pthread线程中会对PProcess是否初始化进行判断,否则不会执行
  3. 编译demo代码,需要先编译安装好ptlib库,下面是我的编译后库的头文件以及库文件
  4. -L ./lib 是链接库的路径lib, -I./include是头文件路径, -lpt_s是链接ptlib库

     

2. 代码实现

#include <stdio.h>
#include "ptlib.h"
#include "ptlib/pprocess.h"

class MyThread1 : public PThread
{
  PCLASSINFO(MyThread1, PThread);
  public:
    MyThread1() : PThread(1000,NoAutoDeleteThread)
    {
      Resume(); // start running this thread when it is created.
      printf("----create thread , resume:\n");
    }

    void Main() {
        int count =0;
        while (!shutdown.Wait(1000)) { // 10ms delay
        std::cout <<"thread count:"<< count << std::endl;
        count++;
        fflush(stdout);
    	Sleep(1000);
      }
    }

    void Start() {
        printf("----start thread:\n");
    }
    void Stop() {
      shutdown.Signal();
    }

    protected:
      PSyncPoint shutdown;
};

class ThreadTest : public PProcess
{
  PCLASSINFO(ThreadTest, PProcess)
  public:
    void Main()
    {
        std::cout <<"ThreadTest start" << std::endl;
        sleep(5);
        std::cout <<"ThreadTest end" << std::endl;
    }
};

int main()
{
    std::cout <<"main start" << std::endl;
    ThreadTest thTest;
    sleep(10);
    std::cout <<"main start thread" << std::endl;
    MyThread1  th1;
    th1.Start();
    sleep(10);
    th1.Stop();
    printf("----main end:");
    std::cout <<"main end" << std::endl;
}

3. 执行编译后的结果

➜  ptlib ./testThread 
main start
main start thread
----create thread , resume:
----start thread:
thread count:0
thread count:1
thread count:2
thread count:3
thread count:4
----main end:main end

可以点击专题头像扫码进入微信群

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值