VC Create Thread

Source: Internet
Author: User
Tags terminates thread class

We often encounter the need to build multiple threads so that we can execute multiple events at the same time. This is our VC development in a foundation, although I have used many times, but also will often forget. This time write down, as a note, for everyone to learn to provide convenience.
In VC, nothing more than creating threads and writing thread functions
One, the conventional method: pure use platform Sdkapi.
1, create the thread:
#include <windows.h>
In MFC, threads are typically created under OnInitDialog ()
Defining Parameters: Serialcontrol
------------------variable function initializes the call area--------
Cserialcontrol * m_serialcontrol=new Cserialcontrol ();
M_serialcontrol->create (NULL, "AA", Ws_child,crect (0,0,0,0), this,2,null);
M_serialcontrol->initallserialport ();
//------------------------------------------------
HANDLE Hthread1=createthread (Null,0,detectcar, (LPVOID) serialcontrol,0,null);
CloseHandle (hThread1); the handle of the thread is closed, but does not mean that the thread is closed, and the thread closes when the program exits
Parameter description:
HANDLE CreateThread (
Lpsecurity_attributes lpthreadattributes,//must be null
DWORD dwstacksize,//typically 0, means the stack is the same size as the external
Lpthread_start_routine lpstartaddress,//thread function name
LPVOID Lpparameter,//arguments passed to the thread function, if more than one, the custom structure body
DWORD dwcreationflags,//0 indicates that the thread starts immediately after the thread is created, and the ResumeThread function is called if it is not started immediately
Lpdword lpthreadid);//To mark the name of the thread

2, define the thread function:
Definition of function
Static DWORD WINAPI Detectcar (LPVOID lpparameter); General use of static functions
Remark: Because the thread function is a static function, if you want to use the object in the function, you must pass the
Implementation of the function
/***************************************************
* Author: Wantian
* Time: 2007-13-03
* Function: Detectcar () Description: Detection thread
****************************************************/
DWORD WINAPI Cissdlg::D etectcar (LPVOID lpparameter)
{
TRACE ("Thread Detectcar is running/r/n");
cserialcontrol* scontrol= (cserialcontrol*) Lpparameter;
Define:record which road is car
int carexit=0;
while (TRUE)//do this forever
{
Get:which Road Exit Car
Carexit=scontrol->m_grouddetector1.carexists ();
***********
}

Method two: Using MFC global functions
cwinthread* AfxBeginThread (Afx_threadproc pfnthreadproc, lpvoid pparam, int npriority = Thread_priority_normal, UINT NS tacksize = 0, DWORD dwcreateflags = 0, lpsecurity_attributes lpsecurityattrs = NULL);

This requires custom Pfnthreadproc (): UINT mycontrollingfunction (LPVOID pparam);
and pass the parameter type .... If you are creating a suspend thread, use Cwinthread->resumethread to perform

Method Three: Use MFC global functions
cwinthread* AfxBeginThread (cruntimeclass* pthreadclass, int npriority = Thread_priority_normal, UINT nStackSize = 0, DWOR D dwcreateflags = 0, lpsecurity_attributes lpsecurityattrs = NULL);
Here you need to derive your own thread class Cmywinthread from the CWinThread class.
CRuntimeClass *rc=runtime_class (cmywinthread) .... You can perform various operations on a thread by using a pointer that returns a CWinThread object.
Method Four: Use your own thread class and create a thread object in the heap
Class Cmywinthread:public cwinthread{...}, to implement your own virtual function run () in a derived class ....
Cmywinthread *mth = new Cmywinthread ()
Mth->create (...) Mth->resumethread ()

DWORD WINAPI Tbegin (LPVOID lpparameter)//Thread call
{
return 0;
}

-----------
DWORD dwthreadid;//
HANDLE h_handle;//Thread

if ((H_handle =createthread (null,0,tbegin,this,0,&dwthreadid)) ==null)
{
MessageBox (_t ("Cannot create thread"));
Return
}
CloseHandle (H_handle);
--------------

6.5 terminating the running of a thread
To terminate the running of a thread, you can use the following method:
? The thread function returns (preferably using this method).
? By calling the E x i t h r e A D function, the thread will undo itself (preferably not using this method).
? The threads in the same process or another process call Te R m i n a t e t h r e a D function (this method should be avoided).
? The process that contains the thread terminates (you should avoid using this method).
The following describes how to terminate a thread's operation and what happens when the thread terminates the runtime.
6.5.1 thread function returns
Threads should always be designed in such a way that they can return when they want the thread to terminate the run. This is
The only way to ensure that all thread resources are properly purged.
If the thread can return, you can ensure that the following items are implemented:
? All C + + objects created in the thread function are correctly undone through their undo functions.
? The operating system will properly release the memory used by the thread stack.
? The system sets the thread's exit code (maintained in the kernel object of threads) to the return value of the thread function.
? The system decrements the usage count of the thread kernel object.
6.5.2 ExitThread function
You can have the thread call the E x i t h r e A D function to force the thread to terminate the operation:
This function terminates the running of the thread and causes the operating system to clear all operating system resources used by the thread. However, the C + + resource (such as the C + + class object) will not be undone. For this reason, it is best to return from the thread function rather than by calling E X i t h r e a D (see chap. 4th for details).
Of course, you can tell the system to set the exit code for the thread by using the E x i t t h R e A D of the D W e x i t t h R e a D parameter. e x i t t h R e A D function does not return any value because the thread has stopped running and cannot execute more code.
Note the best way to stop a thread from running is to have its thread function return. However, if you use the method described in this section, you should know that E x i t h r e A D function is the function that WI n d o W S uses to undo the thread. If you write the C/E + + code, you should never call the X i t t h R e a D. You should use the Visual C + + Run-time Library function _ e n d t h r e a d e x. If you do not use the Visual C + + compiler of M i C R o f t, your compiler vendor has an alternative function of its own e x i t t h R e a D. Whatever this substitution function is, it must be used. The effect of _ E n d t h r e X and its importance is described later in this chapter.
6.5.3 Te R m i n a t e t h r e a D function
Calling Te R m i n a t e t h r e A D function can also terminate the running of a thread:
Chapter 6th Basics of Threading 127
Unlike e x i t t h R e A D, E x i t h r e A D always undoes the calling thread, while te R m i n a t e t h r E A D can undo any thread. The H T H r e A D parameter is used to identify the handle of the thread that is being terminated. When the thread terminates running, its exit code becomes the value you pass as the D w e x i t C o d parameter. Also, the usage count of the thread's kernel objects is decremented.
Note that te R m i n a t e t h r e A D function is a function that runs asynchronously, that is, it tells the system that you want the thread to terminate, but when the function returns, the thread is not guaranteed to be undone. If you need to know exactly what the thread has terminated, you must call the WA i t F o r i n g l e o b J e C T (Introduction to chapter 9th) or similar functions that pass the thread's
Handle.
A well-designed application never uses this function because a thread that is terminated cannot receive a notification that it has been revoked. Threads cannot be purged correctly and cannot prevent themselves from being undone. Note When you undo a thread by using a method that returns or invokes E X i t h r e A D, the memory stack for that thread is also undone. However, if you use Te R m i n a t e t h r e A D, the system does not undo the thread's stack until the process that owns the thread terminates running. M i c R o f t intentionally uses this method to realize te R m i n a t e t h r e a D. If other threads that are still executing are referring to the value on the thread stack that is forcibly undone, then other threads may have an access violation problem. If you leave the stack of a thread that has been undone in memory, other threads can continue to run well. In addition, when a thread terminates running, the D l l usually receives notification. If the thread is forced to terminate using terminate thread, the D l l does not receive notification, which prevents proper cleanup (see Chapter 2nd 0 for more information).
6.5.4 to undo a thread when the process terminates running
The 4th chapter introduces the E x i t P r o C e s S and te R m i n a t e P r o C s function can also be used to terminate the running of a thread. The difference is that these threads will terminate all threads in the running process. In addition, because the entire process has been closed, all resources used by the process must have been purged. This, of course, includes the stack of all threads. These two functions cause the remaining threads in the process to be forcibly undone, just as you would call Te R m n a t e t h r e A D from each remaining thread. Obviously, this means that the correct application cleanup does not occur, i.e. the C + + object Undo function is not invoked, the data does not go to disk, and so on.

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.