Windows Mobile uses Native C ++ to develop multi-threaded programs

Source: Internet
Author: User
Introduction

In the previous article, Windows Mobile used. NET Compact Framework to develop multi-threaded programs. This article describes how to use. NET Compact Framework to develop multi-threaded programs.

 

Implementation environment

Environment: Visual Studio 2008 + Native C ++ WTL 8.1 + Windows Mobile 5.0 R2 professional (VS 2008 built-in) + ARMV4I

 

Class Definition

 

public:
void SendRequest();
void HandleRequest();

private:
HANDLE volatile mHandlerEvent;
HANDLE mHandlerThreadHnd;
DWORD mHandlerThreadId;

HANDLE mRequesterThreadHnd;
DWORD mRequesterThreadId;

MessageQueue mMessageQueue;
CRITICAL_SECTION mLook;

bool volatile mStarted;

private:
void UpdateMessageList(const CString& msg);
void StartThreading();
void StopThreading();

MHandlerEvent is the event to wake up handler thread.

MHandlerThreadHnd is the handler thread's handle.

MHandlerThreadId is the handler thread's Id

MMessageQueue is the shared resource. I use STL queue to encapsulate it.

MLook is a CRITICAL_SECTION object and is used to lock the shared resource.

MHandlerEvent is used to wake up events that process threads.

MHandlerThreadHnd thread handle.

The ID of the mHandlerThreadId thread.

The queue of the mMessageQueue STL, which is used to share data between threads.

MLook is a CRITICAL_SECTION object used for locking between threads.

 

Start two threads
//    Handler thread methods
DWORD WINAPI HanlderThreadProc(void *param)
{
if (param)
{
try
{
CThreadingDemoView* view = (CThreadingDemoView*)param;
view->HandleRequest();
}
catch(...)
{
}
}
return 0;
}

// Requester thread methods
DWORD WINAPI RequesterThreadProc(void *param)
{
if (param)
{
try
{
CThreadingDemoView* view = (CThreadingDemoView*)param;
view->SendRequest();
}
catch(...)
{
}
}
return 0;
}

void CThreadingDemoView::StartThreading()
{
if(!mStarted)
{
UpdateMessageList("Start threading...");
mStarted = true;

InitializeCriticalSection(&mLook);

mHandlerEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // manual reset, initial state is nonsignaled

mHandlerThreadHnd = CreateThread(NULL, 0, &HanlderThreadProc, this, CREATE_SUSPENDED, &mHandlerThreadId);
if (mHandlerThreadHnd)
{
SetThreadPriority(mHandlerThreadHnd, THREAD_PRIORITY_NORMAL);
ResumeThread(mHandlerThreadHnd);
}

mRequesterThreadHnd = CreateThread(NULL, 0, &RequesterThreadProc, this, CREATE_SUSPENDED, &mRequesterThreadId);
if (mRequesterThreadHnd)
{
SetThreadPriority(mRequesterThreadHnd, THREAD_PRIORITY_NORMAL);
ResumeThread(mRequesterThreadHnd);
}
}
}

Initialise some data members such mLook and mHandlerEvent. and start the requester thread and handler thread. I wowould like to pass through the class pointer to the global functions and use member function of the class to run the thread.

Initialize each variable. Then start two threads and pass the object pointer to the static function when starting the thread. In this way, the object method is used for processing. The new thread calls the member functions HandleRequest () and SendRequest () to run and encapsulate all logic in the same class.

 

Requester thread
void CThreadingDemoView::SendRequest()
{
int i = 0;
while(mStarted)
{
if(i > 100)
{
i = 0;
}

Message msg(i, "CPP");
EnterCriticalSection(&mLook);
mMessageQueue.push(msg);
LeaveCriticalSection(&mLook);

// Signal the event
SetEvent(mHandlerEvent);

CString s;
s.Format(_T("%8.8x - %d - %s"), ::GetCurrentThreadId(), msg.mID, msg.mMessageBody);
UpdateMessageList(s);

//sleep 500 milliseconds
Sleep(500);
++i;
}
//printf("Requester thread terminated.\n");
}

Create an object of Message and put it into the queue (mMessageQueue). Use EnterCriticalSection () and LeaveCriticalSection () to lock the shared resource and then wake the handler thread.

Simple processing: The sending request thread can generate a request object, lock it into the shared queue, and then wake up the processing thread through the event.

 

Handler thread
void CThreadingDemoView::HandleRequest()
{
while (mStarted)
{
// Wait for the incomming request
WaitForSingleObject(mHandlerEvent, INFINITE); //INFINITE
ResetEvent(mHandlerEvent);

//Use temp queue to decrease the lock duration.
MessageQueue tempMessageQueue;
EnterCriticalSection(&mLook);
while(!mMessageQueue.empty() && mStarted)
{
tempMessageQueue.push(mMessageQueue.front());
mMessageQueue.pop();
}
LeaveCriticalSection(&mLook);

//procoss the request
while(!tempMessageQueue.empty())
{
CString s;
s.Format(_T("%8.8x - %d - %s"), ::GetCurrentThreadId(), tempMessageQueue.front().mID, tempMessageQueue.front().mMessageBody);
UpdateMessageList(s);
tempMessageQueue.pop();
}

}
//printf("Handler thread terminated.\n");
}

The handler thread will sleep until get the event (mHandlerEvent). Put all the requests to temporary queue and release lock. Display the thread id and message information when process the request.

The processing thread Keeps sleep until it is awakened to the mHandlerEvent event. In actual processing, it may take a long time to process the object. Therefore, to reduce the lock time, put the request in a temporary queue, then process the temporary queue without locks.

 

Stop Threads
void CThreadingDemoView::StopThreading()
{
if(mStarted)
{
UpdateMessageList("Stop threading...");
mStarted = false;

// Signal the event
SetEvent(mHandlerEvent);

// Wait for the Thread to Die
WaitForSingleObject(mHandlerThreadHnd, INFINITE);
CloseHandle(mHandlerThreadHnd);

WaitForSingleObject(mRequesterThreadHnd, INFINITE);
CloseHandle(mRequesterThreadHnd);

DeleteCriticalSection(&mLook);
CloseHandle(mHandlerEvent);

mHandlerEvent = INVALID_HANDLE_VALUE;
mHandlerThreadHnd = NULL;
mHandlerThreadId = 0;
mRequesterThreadHnd = NULL;
mRequesterThreadId = 0;
}
}

Send a signal to stop the thread and clear various objects.

 

A Native C ++ version of multi-thread synchronization and communication program has been completed, you can use it in comparison to Windows Mobile. NET Compact Framework multi-threaded program development, we are very welcome to shot the board, please Pat more, regardless of the program, English description, etc., so that I can continue to improve, get an early offer.

 

Source http://files.cnblogs.com/procoder/ThreadingDemo.zip

 

It may be the last blog post of this month. There is no broadband for migration.

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.