Libjingle thread Mechanism

Source: Internet
Author: User

Libjingle encapsulates all threads, including signaling thread, worker thread, and any other threads. It is packaged using talk_base: Thread. All Thread objects are managed by ThreadManager. ThreadManager can call CurrentThread () anywhere in the Thread to obtain the Thread pointer.

The Thread object inherits MessageQueue and implements a message mechanism similar to windows window. Thread provides Get, Peek, Post, PostDelayed, and other message operation interfaces. To receive messages through MessageQueue, an object must inherit and implement MessageHandler. MessageHandler defines the OnMessage method, which is called in the MessageQueue message.

There are two ways to create a thread

1. autoThread uses the operating system Thread encapsulated by the Thread object of libjingle and makes it the current Thread in the Thread pool of the ThreadManager object. (that is, the cited Thread is returned when Thread: CurrentThread is called)

2. A typical Thread is a worker thread. You must create a Thread object, call ThreadManager: Add or ThreadManager: SetCurrent to Add it to the pool, and call Run to start its circular code, or Start to Start thread listening.

You can send messages to any object in any thread, as long as the object inherits the talk_base: MessageHandler, a simple example is as follows:

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;}

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.