Use Condition variables for inter-thread Communication

Source: Internet
Author: User

Use Condition variables for inter-thread Communication
Recently, I used C ++ to write a communication program under Android and call it to java as a jni library. I encountered a problem using multi-thread round robin:
Thread A receives the data and puts it into the queue as the producer.
Several lines of B, C, and D round-robin training message queues. If the queue has data, it will be taken out for processing. If there is no data, it will be Sleep (T). The problem is how suitable the tvalue is? The processing of large messages is not timely, and the cpu usage of the cell phone increases and the battery usage quickly consumes light.

The optimal solution to this problem is to use conditional variables, which can solve the problem perfectly. The following code uses C ++ encapsulation and uses win32 SDK conditional variables for example. In Linux, there is a completely equivalent concept:

// Thread Message notification class ThreadMsgNotify {// condition variable and critical variable CONDITION_VARIABLE cv _; CRITICAL_SECTION cs _; public: ThreadMsgNotify ();~ ThreadMsgNotify (); int Wait (dword ms); // The Consumer calls this function, blocking Wait milliseconds void Notify (); // The producer calls this function: sends a notification };

The member methods are implemented as follows:

// Threadmsgpolicy: threadmsgpolicy () {InitializeConditionVariable (& cv _); InitializeCriticalSection (& cs _);} threadmsgpolicy ::~ ThreadMsgNotify () {WakeAllConditionVariable (& cv _); // wake up all threads Sleep (50); DeleteCriticalSection (& cs _); DeleteConditionVariable (& cv _);} int ThreadMsgNotify :: wait (dword ms) // consumer, blocked Wait millisecond count {EnterCriticalSection (& cs _); int ret = SleepConditionVariableCS (& cv _, & cs _, MS ); // wait for LeaveCriticalSection (& cs _); return (ret);} void ThreadMsgNotify: Y () // Producer: send notification {EnterCriticalSection (& cs _); wakeConditionVariable (& cv _); // wake up a waiting thread (if any) LeaveCriticalSection (& cs _);}//--------------

The above code is very simple and almost does not need to be explained.

The test code is given below:

Class tagthreadpolicytest {private: list
 
  
MsgList; bool isEnd = false; CRITICAL_SECTION cs _; public: int no; threadmsgy y threadNotify; // thread notification. When receiving a message from a queue, wake up the processing thread tagthreadpolicytest () through this object ();~ Tagthreadpolicytest (); void New (const char * info); // The producer adds a message int Recv (string & msg); // The Consumer reads a message, returns the number of messages in the queue before reading. // The Consumer thread function is static lresult winapi ProcThread (void * lParam) ;}; // The auxiliary function to obtain the current timestamp void CurTime (char * timeStr) {SYSTEMTIME st; GetLocalTime (& st); sprintf (timeStr, "% 02d: % 02d: % 02d. % 03d ", st. wHour, st. wMinute, st. wSecond, st. wMilliseconds);} tagthreadpolicytest: tagthreadpolicytest () {InitializeCri TicalSection (& cs _); // create three consumer threads for (int I = 0; I <3; I ++) {no = I; DWORD dwThreadid; HANDLE thd = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) ProcThread, (void *) this, 0, & dwThreadid); CloseHandle (thd); Sleep (30) ;}} tagthreadpolicytest: :~ Tagthreadpolicytest () {isEnd = true; Sleep (100); DeleteCriticalSection (& cs _) ;}// the producer puts the New message into the queue void tagthreadpolicytest: New (const char * info) {// Insert the queue EnterCriticalSection (& cs _); msgList. push_back (info); LeaveCriticalSection (& cs _); threadpolicy. Y (); // Notify other threads to process data printf ("notify... \ n ") ;}// the consumer reads the message. If no 0int tagthreadpolicytest: Recv (string & msg) {EnterCriticalSection (& cs _); int n = msgList. Size (); if (n> 0) {msg = msgList. front (); msgList. pop_front ();} LeaveCriticalSection (& cs _); return (n);} // consumer thread lresult winapi tagthreadpolicytest: ProcThread (void * lParam) {tagthreadpolicytest * test = (tagthreadpolicytest *) lParam; int no = test-> no; printf ("Thread start, no = % d... \ n ", no); char timeStr [80]; while (! Test-> isEnd) {string msg; int ret = test-> Recv (msg); // read a message CurTime (timeStr); if (ret) {// print printf ("[% d % s] Recv: % s \ n", no, timeStr, msg if any. c_str (); Sleep (1000); // one-second delay to simulate a slow process ;} else {// No printf ("[% d % s]... \ n ", no, timeStr);} // wait for 15 seconds. If there is a notification, the rest test-> threadpolicy will be terminated at any time. wait (15000);} printf ("Thread End: no = % d. \ n ", no); return (1) ;}int main () {// console test program // a new test object, this object will create three consumer threads tagthreadpolicytest * test = new tagthreadpolicytest (); // as the producer thread, it is to receive your buttons, press enter to generate a message while (true) {char s [500]; memset (s, 0,500); gets (s); if (strcmp (s, "exit") = 0) {break ;} if (s [0] = '\ 0') continue; // submit the message test-> New (s) ;}delete test; return (0 );}
 

Both windows and Linux (replaced with the corresponding function) pass the test.

After entering a carriage return, the consumer thread immediately obtains the message and prints it out. If there is no message, the consumer thread waits for 15 seconds and the CPU is very easy.


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.