OpenH323的基礎(chǔ)線程實(shí)現(xiàn)

1. PThread_H323

OpenH323的基礎(chǔ)線程類為PThread_H323。在PThread_H323中定義了一系列關(guān)于線程運(yùn)行參數(shù),例如線程運(yùn)行優(yōu)先級(jí),線程棧大小等。需要注意的一點(diǎn)是,PThread_H323依賴于Ptlib庫(kù)的實(shí)現(xiàn),而PTLib庫(kù)支持多種操作系統(tǒng),所以PThread_H323定義了多個(gè)實(shí)現(xiàn)文件,對(duì)gs_phone來說其使用的實(shí)現(xiàn)文件為libraries/ptlib-2.12.8/src/ptlib/unix/tlibthrd.cxx,在查看代碼時(shí)需要注意這一點(diǎn)(僅示例Linux實(shí)現(xiàn))。
相關(guān)的構(gòu)造函數(shù)如下所示:

//////////////////////////////////////////////////////////////////////////////

//
//  Called to construct a PThread_H323 for either:
//
//       a) The primordial PProcesss thread
//       b) A non-PTLib thread that needs to use PTLib routines, such as PTRACE
//
//  This is always called in the context of the running thread, so naturally, the thread
//  is not paused
//

PThread_H323::PThread_H323(bool isProcess)
  : m_type(isProcess ? e_IsProcess : e_IsExternal)
  , m_originalStackSize(0) // 0 indicates external thread
  , m_threadId(pthread_self())
  , PX_priority(NormalPriority)
#if defined(P_LINUX)
  , PX_linuxId(syscall(SYS_gettid))
#endif
  , PX_suspendMutex(MutexInitialiser)
  , PX_suspendCount(0)
  , PX_state(PX_running)
#ifndef P_HAS_SEMAPHORES
  , PX_waitingSemaphore(NULL)
  , PX_WaitSemMutex(MutexInitialiser)
#endif
{
#ifdef P_RTEMS
  PAssertOS(socketpair(AF_INET,SOCK_STREAM,0,unblockPipe) == 0);
#else
  PAssertOS(::pipe(unblockPipe) == 0);
#endif

  if (isProcess)
    return;

  PProcess::Current().InternalThreadStarted(this);
}


//
//  Called to construct a PThread_H323 for a normal PTLib thread.
//
//  This is always called in the context of some other thread, and
//  the PThread_H323 is always created in the paused state
//
PThread_H323::PThread_H323(PINDEX stackSize,
                 AutoDeleteFlag deletion,
                 Priority priorityLevel,
                 const PString & name)
  : m_type(deletion == AutoDeleteThread ? e_IsAutoDelete : e_IsManualDelete)
//change by Jacky at 20150624 .  c++ do not supprot max with long unsigned int and int. 
//  , m_originalStackSize(std::max(stackSize, 16*PTHREAD_STACK_MIN)) // Set a decent (256K) stack size that won't eat all virtual memory
  , m_originalStackSize(std::max(stackSize, 16*PTHREAD_STACK_MIN)) // Set a decent (256K) stack size that won't eat all virtual memory
  , m_threadName(name)
  , m_threadId(PNullThreadIdentifier)  // indicates thread has not started
  , PX_priority(priorityLevel)
#if defined(P_LINUX)
  , PX_linuxId(0)
#endif
  , PX_suspendMutex(MutexInitialiser)
  , PX_suspendCount(1)
  , PX_state(PX_firstResume) // new thread is actually started the first time Resume() is called.
#ifndef P_HAS_SEMAPHORES
  , PX_waitingSemaphore(NULL)
  , PX_WaitSemMutex(MutexInitialiser)
#endif
{
  PAssert(m_originalStackSize > 0, PInvalidParameter);

#ifdef P_RTEMS
  PAssertOS(socketpair(AF_INET,SOCK_STREAM,0,unblockPipe) == 0);
#else
  PAssertOS(::pipe(unblockPipe) == 0);
#endif
  PX_NewHandle("Thread unblock pipe", PMAX(unblockPipe[0], unblockPipe[1]));

  // If need to be deleted automatically, make sure thread that does it runs.
  if (m_type == e_IsAutoDelete)
    PProcess::Current().SignalTimerChange();

  PTRACE(5, "PTLib\tCreated thread " << this << ' ' << m_threadName);
}

初始化完畢之后,PThread_H323類對(duì)外提供了統(tǒng)一的接口對(duì)線程進(jìn)行啟動(dòng)該接口如下所示:

void PThread_H323::Resume()
{
  Suspend(false);
}

其中Resume接口又調(diào)用了Suspend接口,Suspend接口如下所示:

void PThread_H323::Suspend(PBoolean susp)
{
  PAssertPTHREAD(pthread_mutex_lock, (&PX_suspendMutex));

  // Check for start up condition, first time Resume() is called
  if (PX_state == PX_firstResume) {
    if (susp)
      PX_suspendCount++;
    else {
      if (PX_suspendCount > 0)
        PX_suspendCount--;
      if (PX_suspendCount == 0)
        PX_StartThread();
    }

    PAssertPTHREAD(pthread_mutex_unlock, (&PX_suspendMutex));
    return;
  }

#if defined(P_MACOSX) && (P_MACOSX <= 55)
  // Suspend - warn the user with an Assertion
  PAssertAlways("Cannot suspend threads on Mac OS X due to lack of pthread_kill()");
#else
  if (!IsTerminated()) {

    // if suspending, then see if already suspended
    if (susp) {
      PX_suspendCount++;
      if (PX_suspendCount == 1) {
        if (m_threadId != pthread_self()) {
          signal(SUSPEND_SIG, PX_SuspendSignalHandler);
          pthread_kill(m_threadId, SUSPEND_SIG);
        }
        else {
          PAssertPTHREAD(pthread_mutex_unlock, (&PX_suspendMutex));
          PX_SuspendSignalHandler(SUSPEND_SIG);
          return;  // Mutex already unlocked
        }
      }
    }

    // if resuming, then see if to really resume
    else if (PX_suspendCount > 0) {
      PX_suspendCount--;
      if (PX_suspendCount == 0) 
        PXAbortBlock();
    }
  }

  PAssertPTHREAD(pthread_mutex_unlock, (&PX_suspendMutex));
#endif // P_MACOSX
}

Suspend函數(shù)中調(diào)用了PX_StartThread,這個(gè)函數(shù)負(fù)責(zé)真正線程的建立,設(shè)置線程的相關(guān)屬性等并將線程投入運(yùn)行狀態(tài),如下所示:

void PThread_H323::PX_StartThread()
{
  // This should be executed inside the PX_suspendMutex to avoid races
  // with the thread starting.
  PX_state = PX_starting;

  pthread_attr_t threadAttr;
  pthread_attr_init(&threadAttr);
  PAssertPTHREAD(pthread_attr_setdetachstate, (&threadAttr, PTHREAD_CREATE_DETACHED));

#if defined(P_LINUX)

  pthread_attr_setstacksize(&threadAttr, m_originalStackSize);

  struct sched_param sched_params;
  PAssertPTHREAD(pthread_attr_setschedpolicy, (&threadAttr, GetSchedParam(PX_priority, sched_params)));
  PAssertPTHREAD(pthread_attr_setschedparam,  (&threadAttr, &sched_params));

#elif defined(P_RTEMS)
  pthread_attr_setstacksize(&threadAttr, 2*PTHREAD_MINIMUM_STACK_SIZE);
  pthread_attr_setinheritsched(&threadAttr, PTHREAD_EXPLICIT_SCHED);
  pthread_attr_setschedpolicy(&threadAttr, SCHED_OTHER);
  struct sched_param sched_param;
  sched_param.sched_priority = 125; /* set medium priority */
  pthread_attr_setschedparam(&threadAttr, &sched_param);
#endif

  PProcess & process = PProcess::Current();

  // create the thread
  PAssertPTHREAD(pthread_create, (&m_threadId, &threadAttr, &PThread_H323::PX_ThreadMain, this));

  // put the thread into the thread list
  process.InternalThreadStarted(this);

  pthread_attr_destroy(&threadAttr);

#ifdef P_MACOSX
  if (PX_priority == HighestPriority) {
    PTRACE(1, "set thread to have the highest priority (MACOSX)");
    SetPriority(HighestPriority);
  }
#endif
}

其中線程中執(zhí)行的函數(shù)為PX_ThreadMain,該函數(shù)的實(shí)現(xiàn)如下:

void * PThread_H323::PX_ThreadMain(void * arg)
{
  PThread_H323 * thread = reinterpret_cast<PThread_H323 *>(arg);

#if P_USE_THREAD_CANCEL
  // make sure the cleanup routine is called when the threade cancelled
  pthread_cleanup_push(&PThread_H323::PX_ThreadEnd, arg);
#endif

  thread->PX_ThreadBegin();

  // now call the the thread main routine
  thread->Main();

#if P_USE_THREAD_CANCEL
  pthread_cleanup_pop(1); // execute the cleanup routine
#else
  PX_ThreadEnd(arg);
#endif

  return NULL;
}

可以看到該函數(shù)實(shí)際執(zhí)行了Main函數(shù),該函數(shù)為虛函數(shù),供外部調(diào)用,從而實(shí)現(xiàn)相關(guān)的功能。PX_ThreadBegin僅僅執(zhí)行了一些校驗(yàn),并且做了一些線程投入運(yùn)行前的準(zhǔn)備工作。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容