MFC-based writing thread Quick Start

Source: Internet
Author: User
Tags protected constructor

MFC-based writing thread Quick Start
ProgramMember's house Author: Unknown Date: 19:19:00

--------------------------------------------------------------------------------
 
For beginners, I don't know where to start writing threads or what to do with writing threads. Below is a brief framework of a thread.

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

// Define the Thread class yourthread. h
# If! Defined (yourthread_include_file)
# Define yourthread_include_file

Class cyourthread: Public cwinthread
{
....
Declare_dyncreate (cyourthread)
Public:
Cyourthread (); // protected constructor used by Dynamic Creation

// Attributes
Public:
Int m_bcloseflag;
Handle m_heventkill;
Handle m_heventdead;
// Operation
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
// Implementation
Public:
Virtual ~ Cyourthread ();

// Generated message map Functions
// {Afx_msg (cegclientcachethread)
// Note-The classwizard will add and remove member functions here.
//} Afx_msg

Declare_message_map ()
}
# Ednif

//////////////////////////////////////// ////
// Implement the file yourthread. cpp
# Include "stdafx. H"
# Include "yourthread. H"

# Ifdef _ debug
# Define new debug_new
# UNDEF this_file
Static char this_file [] = _ file __;
# Endif
Implement_dyncreate (cyourthread, cwinthread)
Cyourthread: cyourthread ()
{
M_bautodelete = false; // Note: if the member is a member of cwinthread, for example, true, the thread will be deleted in cwinthread: delete ().
// If it is set to false, the thread cannot be automatically deleted.

M_heventkill = createevent (null, true, false, null );
M_heventdead = createevent (null, true, false, null );
}

Cyourthread ::~ 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 return true

// If it is a worker thread,CodeAs follows:
/*
While (waitforsingleobject (m_heventkill, 0) = wait_timeout)
Singlestep ();
// To avoid entering the standard message loop, false must be returned
Return false;
*/
}

Cyourthread: singlestep ()
{
// The task that your thread must execute once. Every time your thread gets control, this function will be executed.
}

// If it is a user interface thread, the following function must be reloaded
Int cyourthread: Run
{
// Note: the front-end code is completely consistent with cwinthread: Run () except for the explanation in Chinese.
// For tracking the idle time state
Assert_valid (this );

// For tracking the idle time state
Bool bidle = true;
Long lidlecount = 0;

// Acquire and dispatch messages until a wm_quit message is wrongly ed.
For (;;)
{
Singlestep (); // executes the single-step function of this thread.
If (m_bcloseflag = true) // indicates that the thread is disabled.
{
Return exitinstance ();
}
// Phase2: pump messages while available
// Message loops must be performed in the following ways, because casyncsocket uses a standard Windows message loop to process data sending and receiving income.
While (: peekmessage (& m_msgcur, null, pm_noremove) // you must use peekmessage to check the message.
{
If (! (: Getmessage (& m_msgcur, null) // retrieves the message
Return exitinstance ();

If (! Pretranslatemessage (& m_msgcur ))
{
: Translatemessage (& m_msgcur );
: Dispatchmessage (& m_msgcur );
}

If (isidlemessage (& m_msgcur ))
{
Bidle = true;
Lelecount = 0;
}

}
 
}
Return exitinstance ();

}

Int cyourthread: exitinstance ()
{
// If it is a user interface thread, you can clear the task here

Verify (setevent (m_heventdead); // This sentence is only required by the user interface thread

Return cwinthread: exitinstance ();

}

Void cyourthread: delete ()
{
// Calling the base here won't do anything but it is a good habit ?????????????

// In cwinthread: delete (), if m_hautodelete is set to true, the process will be deleted.
Cwinthread: delete ();

// Acknowledge receipof kill notification
Verify (setevent (m_heventdead ));
}

Void cyourthread: killthread ()
{
// Note: This function is called in the context 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 following two rows can only be required by the worker thread
/*
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_susponded )))
{
Afxmessagebox (_ T ("failed to create thread "));
Return;
}

Verify (pthread-> setthreadpriority (thread_priority_idle); // sets the priority.

Pegthread-> resumethread (); // start the thread
}

//////////////////////////////////////// ///////////////
// The following is an explanation
Note:
1 thread is divided into two categories: worker thread and user interface thread

2. the user interface thread can perform user interaction such as keyboard input, but the worker thread does not. Of course there are also differences in the message processing mechanism.
3. It is also different in thread initialization. The above example
4. The job thread and the user interface thread are also purged on the reused thread.

5. Resource Conflicts must be solved when multiple threads are involved. When learning to write a thread, you can use the critical method to solve this problem.

Define a global variable externally

Critical_section m_csyourthreadlock; // thread synchronization lock

Initialization during the call:

Initializecriticalsection (& m_csyourthreadlock)

After exiting all threads

Deletecriticalsection (& m_csyourthreadlock)

 

In the singlestep () function, add this critical lock to the processing of shared resources.

Void cyourthread: singlestep ()

{

Entercriticalsection (& m_csyourthreadlock );

// Share resource processing code

Leavecriticalsection (& m_csyourthreadlock );

// Other code

}

 

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.