MFC-based writing thread rapid entry

zhaozj2021-02-16  55

For new hands, writing threads, I don't know where to start, I don't know what to write threads, and give a brief framework for a thread.

//

// Define threaded class YourThread.h # if! Defined (YOTHREAD_INCLUDE_FILE) #define yourRead_include_file

Class CyouRThread: Public Cwinthread {.... declare_dyncreate (cyouRThread) public: cyouRThread (); // protected constructor used by Dynamic Creation

// attributespublic: int m_bcloseflag; handle m_heventkill; handle m_heventdead; // Timing public: void killthread (); // Clear this thread

protected: virtual void SingleStep (); virtual void Delete (); // Overrides // ClassWizard generated virtual function overrides // {{AFX_VIRTUAL (CEgClientCacheThread) public: virtual BOOL InitInstance (); virtual int ExitInstance (); virtual int Run ( ); //}} AFX_VIRTUAL // ImplementationPublic: Virtual ~ cyouRead ();

{{{AFX_MSG (CEGCLIENTCACHETHREAD) // Note - The ClassWizard Will Add and Remove Member functions here. //}} AFX_MSG

Declare_MESSAGE_MAP ()} # Ednif

// Implement the file youRhread.cpp # include "stdafx.h" #include "youRThread.h"

#ifdef _DEBUG # define new DEBUG_NEW # undef THIS_FILEstatic char THIS_FILE [] = __FILE __; # endifIMPLEMENT_DYNCREATE (CYourThread, CWinThread) CYourThread :: CYourThread () {m_bAutoDelete = FALSE; // NOTE: This is a member of CWinThread member, such as is TRUE, In CWINTHREAD :: Delete () will delete threads // is set to FALSE does not allow automatic deletion of thread

m_heventkill = CreateEvent (Null, True, False, Null); m_heventdead = CreateEvent (Null, True, False, NULL);

CYOOTHREAD :: ~ cyouRThread () {

CloseHandle (m_hEventKill); CloseHandle (m_hEventDead);} BOOL cYourThread :: InitInstance () {// TODO: perform and per-thread initialization here // avoid entering standard message loop by returning FALSE return TRUE; // user interface thread, must Returns True // If you work thread, the code is as follows / * while (WaitForsingleObject (m_heventkill, 0) == Wait_timeout) SINGLESTEP (); // Avoid enter the standard message loop, must return false returnaf false; * /} cyouRThread: SingLESTEP () {// Your thread must be executed once, every time your thread is controlled, you will execute this function. }

/ / If the user interface thread, the following functions must be overloaded: Run {// Note: In addition to filling Chinese explains, other Cwins :: Run () is exactly uniform // for tracking The iDLE Time State Assert_Valid (this);

// for tracking the iDLE Time State Bool Bidle = true; long LidleCount = 0;

// acquire and dispatch message is receivated. for (;;) {SingLESTEP (); // Perform this thread single-step function if (m_bcloseflag == true) // indicates the thread to turn off {Return EXITINSTANCE (); } // Phase2: Pump message While Available // must be used in the following way, because CasyncSocket uses a standard Windows message loop to process data send and receive while (:: PeekMessage (& M_MSGCur, Null, Null, Null, PM_NOREMOVE ))) // must first use PeekMessage to check {if (! (:: getMessage (& m_msgcur, null, null)) // Take Message Return EXITINSTANCE ();

IF (! PretranslateMessage) {:: TranslateMessage ;: DispatchMESSAGE (& M_MSGCUR);

IF (isidleMessage) {bidle = true; lidlevount = 0;}

}}} Return EXITINSTANCE ();

}

INT CYOOTHREAD :: EXIXSTANCE () {// If the user interface thread, you complete your clear task

Verify (STEVENT (M_HEVENTDEAD)); // This sentence is only available for user interface threads

Return CWINTHREAD :: EXITINSTANCE ();

}

Void cyorthread :: delete () {// calling the base here is a good habit ????????????? // in cwinthread :: delete () such as M_HAUTDELETE True, you will delete this process cwinthread :: delete ();

// Acknowledge receipt of kill notification verify (set ");}

Void CyouRThread :: Killthread () {// Note: this function is caled in the content of other threads, // NOT The Thread Itself.

// reset the m_heventkill Which signals the thread to shutdown verify (setevent (m_heventkill);

// Allow Thread to Run At Higher Priority During Kill Process SetthreadPriority (Thread_Priority_above_NORMAL); WaitForsingleObject (m_heventdead, infinite);

// The next two lines only worker threads can be / * WaitForSingleObject (m_hThread, INFINITE); delete this; * /} // start the thread void startYourThread () {CEgYourThread * pThread;! If ((pThread = (CYourThread *) AfxBeginThread ( Runtime_class (cyouRThread), Thread_Priority_NORMAL, 0, CREATE_SUSPENDED)) {AFXMessageBox (_T ("Create Thread Failed")); Return;}

Verify (pthread-> setthreadpriority (thread_priority_idle)); // Set the priority pegthread-> resumethread (); // start thread}

///// below is explained: 1 Thread division two categories: work thread and user interface thread

2 User interface threads can perform user interactions such as keyboard input, while the working thread is not. Of course, there is also a difference in message processing mechanisms. 3 The initialization is also different. As described above 4 On the repeated thread, the working thread is not the same as the user interface thread.

5 Multi-thread, you must solve the problem of resource conflicts. When you start learning to write thread, you can use critical law to solve this problem.

Define a global variable outside

Critical_section m_csyouRThreadLock; // Thread synchronization lock

Initialize during call:

InitializeCriticalSection (& m_csyouRThreadlock)

After exiting all threads

DeletecriticalSection (& m_csyouRThreadlock)

In the SINGLESTEP () function, the processing of shared resources, plus this critical lock

Void cyouRThread :: SINGLESTEP ()

{

EntercriticalSection (& M_CSYOTHREADLOCK);

// Share resource processing code

LeavecriticalSection (& M_CSYOTHREADLOCK);

// Other code

}

转载请注明原文地址:https://www.9cbs.com/read-24335.html

New Post(0)