本文主要写基于ptlib写一个使用线程的demo示例,可以实际运行起来
1. demo编译:
g++ thread.cxx -lpt_s -lpthread -lresolv -ldl -L ./lib -I./include -o testThread
注意:
- 创建线程后,需要调用Resume()函数来执行线程(可以在构造函数或者start方法调用)
- 使用ptlib的线程,必须先要有一个PProcess的实例,表示一个应用程序,所化PProcess再创建线程,pthread线程中会对PProcess是否初始化进行判断,否则不会执行
- 编译demo代码,需要先编译安装好ptlib库,下面是我的编译后库的头文件以及库文件
- -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
可以点击专题头像扫码进入微信群