webrtc thread introduce
1,webrtc thread常用到的类有MessageHandler,Thread。
2,MessageHandler用来作为线程处理函数的回调,实现如下:
class MessageHandler {
public:
virtual void OnMessage(Message* msg) = 0;
protected:
MessageHandler() {}
virtual ~MessageHandler();
private:
DISALLOW_COPY_AND_ASSIGN(MessageHandler); //禁掉copy和赋值方法
};
3,假设类A要使用webrtc的thread,那么使用方式如下:
class A:public MessageHandler{
public:
A():mThread(Null){
mThread = new(std::nothow) talk_base::Thread();
if(mThread){
mThread->start();
}
};
~A(){
if(mThread){
mThread->stop();
delete mThread;
mThread = Null;
}
}
void Test(string&test){
mThread->post(this,MSG_THREAD_TEST,new MessageData(test));
}
private:
enum {
MSG_THREAD_TEST
};
void OnMessage(talk_base::Message* msg){
switch(msg->message_id){
case MSG_THREAD_TEST:{
MessageData * obs = static_cast<MessageData*>(msg->pdata);
//TODO
OnTest(obs->name);
delete obs;
}
break;
default:
break;
}
}
// 在thread中执行
void OnTest(string&test){
}
Thread* mThread;
}
//direction for use
A a;
a.Test("test");
4,thread中方法说明:
- start(),线程启动;
- restart(),重启线程;
- stop(),线程停止;
- post(),异步执行指定的事件;
- send(),同步执行指定的事件;
- PostDelayed(),异步延时执行指定的事件;
- clear(),清空队列中的消息;
有一点需要注意stop()后不能再次start(),需要调用restart();