设为首页 加入收藏

TOP

libjingle线程机制
2014-07-19 23:03:19 来源: 作者: 【 】 浏览:86
Tags:libjingle 线程 机制

  libjingle包装了所有的线程,包括signaling thread,worker thread, 和其它任何线程,用talk_base::Thread来包装。所有的 Thread对象由ThreadManager来管理 ,ThreadManager可以在线程内任意地方调CurrentThread()用来获取线程指针。

  Thread对象继承了MessageQueue实现了类似于windows窗口消息机制,Thread提供了Get、Peek、Post、PostDelayed等一系列消息操作的接口。一个对象想通过MessageQueue接收消息必须继承并实现MessageHandler。MessageHandler定义了OnMessage方法,这个方法在MessageQueue消息中调用。

  有两种创建线程的方法

  1.AutoThread 用libjingle的Thread对象包装的操作系统线程,并使它成为ThreadManager对象的线程池中的当前线程,(也就是说,当用Thread::CurrentThread调用时返回引线程)

  2.Thread 典型用为worker thread,必须创建一个Thread 对象,调用ThreadManager::Add或者ThreadManager::SetCurrent来将它加入池,并调用Run来开始它的循环代码,或者Start来开始线程监听。

  你可以向任何线程的任何对象发送消息,只要这个对象继承了talk_base::MessageHandler简单的示例如下:

  class Test:public talk_base::MessageHandler

  {

  public:

  Test()

  {i=0;}

  void OnMessage(talk_base::Message *pmsg)

  {

  if (pmsg->message_id==50)

  {

  talk_base::Thread * curThread=talk_base::Thread::Current();

  printf("thread run count=%d threadId=%d\n",++i,curThread->GetThreadId());

  }

  }

  int i;

  };

  int _tmain(int argc, _TCHAR* argv[])

  {

  talk_base::Thread thread;

  thread.Start();

  Test test;

  for (int i=0;i<100;++i)

  {

  Sleep(30);

  thread.Post(&test,i);

  }

  getchar();

  return 0;

  }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇类似Common Lisp的多参数加法 下一篇C++继承与面向对象设计

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·CPython是什么?PyPy (2025-12-26 06:50:09)
·Python|如何安装seab (2025-12-26 06:50:06)
·python要学习数据分 (2025-12-26 06:50:03)
·每日一道面试题-多线 (2025-12-26 06:20:17)
·java项目中哪些地方 (2025-12-26 06:20:14)