1. Create a simple worker thread;
In the view class, add the message map function to the mouse:
AfxBeginThread ((Afx_threadproc) testthread,this);
Then join the thread's entry function in the view class:
UINT Testthread (LPVOID pparam)
{
AfxMessageBox ("This is a dialog box for test worker threads");
return 0;
}
Function Description:
cwinthread* AfxBeginThread (Afx_threadproc pfnthreadproc, lpvoid pparam, int npriority = Thread_priority_normal, UINT nSt acksize = 0, DWORD dwcreateflags = 0, lpsecurity_attributes lpsecurityattrs = NULL);
cwinthread* AfxBeginThread (cruntimeclass* pthreadclass, int npriority = Thread_priority_normal, UINT nStackSize = 0, DWOR D dwcreateflags = 0, lpsecurity_attributes lpsecurityattrs = NULL);
Pfnthreadproc:
A control function that points to a worker thread, cannot be null, and the function must be defined as follows:
UINT mycontrollingfunction (LPVOID pparam);
The Runtime_class object of the Pthreadclass:cwinthread.
Pparam: Arguments passed to the control function.
Npriority: Thread priority, function can be used
BOOL SetThreadPriority (
HANDLE hthread,//HANDLE to the thread
int npriority//thread priority level
); To set
Nstacksize: The size of the stack, if 0, is the same size as the main thread that was created.
Dwcreateflags: An additional flag when creating a thread, which can be create_suspended, which represents a pending thread until a DWORD ResumeThread () is called, and the function is executed at 0, indicating immediate execution.
Lpsecurityattrs: Points to a security_attributes describes the security of the thread, which can be null if the same security properties as the main thread.
You can also use the member function of the CWinThread class
BOOL CreateThread (DWORD dwcreateflags = 0, UINT nstacksize = 0, lpsecurity_attributes lpsecurityattrs = NULL); To create a thread, specifically The same parameters as above.
You can also use the API to create threads:
HANDLE CreateThread (
Lpsecurity_attributes lpthreadattributes,//Pointer to security ATTRIBUTES
DWORD Dwstacksize,//initial thread stack size
Lpthread_start_routine lpstartaddress,//pointer to thread function
LPVOID Lpparameter,//argument for new thread
DWORD dwcreationflags,//Creation Flags
Lpdword Lpthreadid//Pointer to receive thread ID
);
DWORD WINAPI Yourthreadfunc (lpvoidlpvthreadparm);
lpthreadid:32 identifier, used to receive the label of the thread
The function returns a handle to the created thread.
2. How to end a thread:
void AfxEndThread (UINT nexitcode);//end the currently running thread.
Nexitcode: Exit code for thread.
BOOL TerminateThread (
HANDLE hthread,//HANDLE to the thread
DWORD Dwexitcode//exit code for the thread
);
If a thread calls void ExitThread (Uintfuexitcode), it can also terminate
3. How to get the thread exit code;
Using functions
BOOL GetExitCodeThread (
HANDLE hthread,//HANDLE to the thread
Lpdword Lpexitcode//address to receive termination status
);
4. Set the priority of the thread;
BOOL SetThreadPriority (
HANDLE hthread,//HANDLE to the thread
int npriority//thread priority level
);
npriority; thread priority, with: Thread_priority_above_normal,thread_priority_below_normal,thread_priority_highest,thread_ Priority_idle,thread_priority_lowest,thread_priority_normal,thread_priority_time_critical specific functions are described in MSDN.
We can set the priority in the worker thread created above:
SetThreadPriority (GetCurrentThread (), thread_priority_highest);//set two points higher than usual
5. How to create multi-threaded multitasking.
You can call to create a function with the above thread, pass it to a different parameter of the same thread function, or start another thread.
6. Suspend and Resume Threads:
I mentioned earlier that you can create a thread that is suspended (by passing the CREATE_SUSPENDED flag to the function CreateThread). When you do this, the system creates the core object of the specified thread, creates the thread's stack, and initializes the thread CPU registration member in the context structure. However, the thread object is assigned an initial suspend count value of 1, which indicates that the system will no longer allocate CPU to execute the thread. To start executing a thread, a thread must call ResumeThread and pass it to the thread handle that is returned when it calls CreateThread.
DWORD ResumeThread (HANDLE hthread);
A thread can be suspended multiple times. If a thread is suspended 3 times, the thread must be restored 3 times before it is allocated the CPU. In addition to using the CREATE_SUSPENDED flag when creating threads, you can also suspend threads with the SuspendThread function.
Dwordsuspendthread (HANDLE hthread);
7. Use of thread synchronization objects;
Synchronization objects are: critical_section (critical section), event (events), mutex (mutex object), semaphores (semaphore). There are corresponding API creation functions and MFC classes, the synchronization object can be in two states: signal State (signal State) or non-signaled status, when a thread is associated with an object, if the object is in a non-signaled state, it will wait until it becomes a signal state thread to continue execution.
The WIN32 API provides the wait command WaitForSingleObject and waitformutipleobjects:
DWORD WaitForSingleObject (
HANDLE hobject,//Handle of object to wait
DWORD dwmilliseconds); Maximum wait time (milliseconds)
DWORD WaitForMultipleObjects (
DWORD dwnumobjects,//Number of objects to wait
Lphandle lphandles,//array of object handles
BOOL bWaitAll,//whether to wait for all objects to have a signal before returning
DWORD dwmilliseconds); Maximum wait time
If the object reaches the signal state within the specified time, it returns WAIT_OBJECT_0, the timeout returns wait_timeout, and an error returns wait_failed. For mutex, semaphore, and Auto Reset (Auto-reset) event objects, wait for success to change them to a non-signaled state (semaphore counter minus 1) to achieve mutually exclusive access to the object.
Pieces: Jianuangzhiganhue
8. Event:
"Event"--a synchronization object that allows a thread to notify another thread when an event occurs. Events are useful when a thread needs to know when to perform a task.
There are two types of CEvent objects: Automatic and Manual. A manual CEvent object exists in the state set by resetevent or setevent until another function is called. An automatic CEvent object automatically returns an unmarked (useless) state after at least one thread has been freed.
CEvent (bool Binitiallyown = FALSE, bool bManualReset = False, LPCTSTR lpszName = NULL, lpsecurity_attributes lpsaattribut e = NULL);
Binitiallyown; If true, the CMultiLock or CSingleLock object can be used, false, and the thread must wait until the required resource is freed.
bManualReset: True, set to manual reset event object, False, set to auto reset event object.
LpszName: Name of event object, cannot specify an object that already exists
Lpsaattribute: Security Properties for event objects
Multiple synchronous Access objects related to the synchronization object CMultiLock and a single synchronized Access Object CSingleLock object.
CSingleLock (csyncobject* pobject, BOOL binitiallock = FALSE);
Pobject: Point to a synchronization object to be processed
Binitiallock: Specifies whether to attempt to access the object at the initial time.
CMultiLock (csyncobject* ppobjects[], DWORD dwcount, BOOL binitiallock = FALSE);
Dwcount: Specifies the number of synchronization objects, which must be greater than 0.
Here's a brief description of their application:
Call this member function to construct a named or unnamed CEvent object. To access or release a CEvent object, you can create a CSingleLock or CMultiLock object and invoke its lock and unlock member functions. To change the state of the CEvent object to marked (a thread without waiting), you can call SetEvent or pulseevent. To set a CEvent object to be untagged (a thread that must wait), call resetevent.
You can start setting up cevent::setevent on your thread, and other threads will use Csinglelock::lock to wait for the end of your thread processing. When your thread finishes processing and the event is cleared with Cevent::resetevent, the other program can continue to execute.
API functions:
HANDLE CreateEvent (
Lpsecurity_attributes LPSA,//security attribute pointer, Win98 ignored
BOOL Bmanualrest,//whether manual reset (manual-reset)
BOOL Binitialstate,//whether the initial state is a signal state
LPCTSTR lpname); Object name string pointer
The auto-reset (Auto-reset) event and the manual Reset (manual-reset) event, which is specified by the second parameter of CreateEvent (). For automatic reset events, WaitForSingleObject () and waitformultipleobjects () wait for the event to signal state and then automatically reset it to a non-signaled state, which guarantees that only one of the threads waiting for this event will be awakened. A manual reset event requires the user to call ResetEvent () to reset the event. There may be several threads waiting for the same event, so that all waiting threads can run when the event becomes signaled. The SetEvent () function is used to set the event object to signal state, and resetevent () resets the event object to a non-signaled state, both of which require an event object handle as a parameter.
9. Critical section
Only one thread is allowed to access a resource or code area at a time. Critical sections are useful for controlling only one thread at a time to modify data or other control resources. When running performance is important and resources are not used across processes, it is recommended to use a critical section instead of a semaphore. For more information about using Semaphores in MFC, see CMutex. You need to construct it before using the CCriticalSection object. After the constructor returns, you can use the critical section. Call the Unlock function after you have finished using it. When accessing resources controlled by ccriticalsection, a variable of type CSingleLock is defined in the Access function of the resource. The lock member function (such as csinglelock::lock) that locks the object is then called. At this point, the calling thread either gets access to the resource, waits for someone to release the resource to wait for the lock, or waits for someone else to release the resource, but the lock fails because of a timeout. This ensures that only one thread is accessing the critical resource at a time. Releasing a resource simply calls the member function Unlock (for example, Csinglelock:unlock), or lets the lock object outside the scope of action.
In addition, you can create an CCriticalSection object independently and access it explicitly before accessing the critical resource. This approach helps keep the code clear, but is more error-prone, because remember to lock before accessing critical resources and unlock after access.
Constructor: CCriticalSection ();
member function: BOOL Lock (); BOOL Lock (DWORD dwtimeout); This function is used to obtain access rights to the critical section object. Lock is a block operation that returns only if access to the critical section object is obtained.
Virtual BOOL UnLock (); If the critical section is occupied by this thread and the lock succeeds, a value other than 0 is returned. Otherwise, it is 0. This function frees the CCriticalSection object that the thread occupies. If CCriticalSection is used alone, the unlock lock should be called as soon as possible after the exclusive use of the critical resource. If the CSingleLock object is used, Ccriticalsection::unlock will be called in its member function unlock.
API functions:
Critical_section CS; Then initialize, call the following function (the pointer to the null object for the argument):
VOID initializecriticalsection (lpcritical_section lpcs);
VOID entercriticalsection (lpcritical_section lpcs); Enter and leave the critical section to invoke the function separately:
VOID leavecriticalsection (lpcritical_section lpcs);
VOID deletecriticalsection (lpcritical_section lpcs); Delete a critical section object by:
Ten. Mutex (Mutex object)
It is a synchronization object that allows a thread to access the same resource together. When only one thread is allowed to modify data or other controlled resources.
One way to use a CMutex object is to have a variable of type CMutex as a data member of the class you want to control. In the construction of the controlled object, if the mutex object initially has the name of the mutex object or the expected security attribute, then the constructor specified by the CMutex data member is called to access the resources controlled by the CMutex object in this way. You first create a variable of type CSingleLock or CMultiLock type in the member function of the resource access. Then call the lock member function that blocks the object (for example, Csinglelock::lock). In this way, your thread will either gain access to the resource, wait for the resource to be freed, gain access, or wait for the resource to be freed, and return failure after the timeout. In either case, resources can be accessed in a thread-safe mode. To dispose of these resources, use the Unlock member function that blocks the object (for example, Csinglelock::unlock), or allow the blocking object to be out of bounds.
CMutex (BOOL binitiallyown = FALSE, lpctstr lpszName = null,lpsecur-ity_attributes Lpsaattribute = NULL);
Binitiallyown: Specifies whether the thread that created the CMutex object initially has access to the resource controlled by the mutex.
The name of the Lpszname:cmutex object. If the other mutex is the same name, then you must provide lpszname so that the object can pass through the process boundary. If the value is null, the mutex is not named. If the name matches a mutually exclusive object that already exists, the constructor creates a new CMutex object that references the name of the mutex object. If the name matches a synchronization object that already exists that is not a mutex, the construction process will fail.
Lpsaattribute: Security for objects
API functions:
HANDLE CreateMutex (
Lpsecurity_attributes LPSA,//Security attribute pointer
BOOL Binitialowner,//TR UE indicates that the thread will own the semaphore
LPCTSTR lpname); Object Name
In other processes, CreateMutex () and OpenMutex () can be invoked with the same mutex name to open the object, so that the mutex can be used in more than one process, and the thread passes through the WaitForSingleObject () and Waitformultipleobject () to wait for a mutex, with ReleaseMutex () to release a mutex.
11. Semaphores (semaphore)
A CSemaphore class object represents a "signal" a synchronization object that allows a limited number of threads to access the same resource in one or more processes. A semaphore object maintains a count of the threads that are currently accessing a specified resource.
CSemaphore is useful for a shared resource that can only support a limited number of users.
The current count of CSemaphore objects is the number of other users that can also be allowed. When this count reaches 0, all access attempts to the resource controlled by the CSemaphore object are inserted into a system queue until they run out of time or the count value is no longer zero. The maximum number of users to which this controlled resource can concurrently accept access is specified during the construction of the CSemaphore object.
Another way to use the CSemaphore object is to add a variable of type CSemaphore to the class you want to control as a data member. During the construction of the controlled object, the constructor of the CSemaphore data member is called to specify the initial value of the access count, the maximum value of the access count, the name of the signal (if it is to be used throughout the process), and the security flags that are required. To access resources controlled in this way by the CSemaphore object, first create a variable of type CSingleLock or CMultiLock in the Access member function of your resource. Then call the lock member function of the locking object (for example, Csinglelock::lock). At this point, your thread will gain access to the resource, wait for the resource to be freed and access it, or the access to the resource fails when it waits for the resource to be freed. In either case, your resources are accessed in a thread-safe (thread-safe) manner. To release a resource, you can use the Unlock member function of the lock object (for example, Csinglelock::unlock), or let the lock object go beyond the scope.
CSemaphore (Long lInitialCount = 1, long lmaxcount = 1, lpctstr pstrname= NULL, Lpsecurity_attributes lpsaattributes = NULL);
lInitialCount: The initial use count of the signal. must be greater than or equal to 0, and less than or equal to Lmaxcount.
Lmaxcount: The maximum value of the usage count for the signal. must be greater than 0.
Pstrname: The name of the signal. If this signal is to be accessed throughout the process, you must provide this name. If it is null, the object will be without a name. If the name is the same as the name of an already existing signal, the constructor creates a new CSemaphore object that references the object with that name. If the name is the same as the name of a synchronous object that already exists but is not a signal, the constructor fails.
API usage:
HANDLE CreateSemaphore (
Lpsecurity_attributes lpsecattr,//Security attribute pointer
LONG INITIALCOUTN,//initial semaphore number
LONG Lmaxcount,//maximum number of semaphores allowed
LPCTSTR lpszsemname); Semaphore Object name pointer
When the number of semaphores is greater than 0 o'clock, it is in the signal state. If the Lpszsemname parameter is NULL, the semaphore is confined to the thread of a process, and if a string object name is given, the semaphore can also be used by other processes. Other processes can be called createsemaphore () and OpenSemaphore () when the string is a parameter to open the semaphore, so that you can achieve synchronization between multiple processes. WaitForSingleObject () and WaitForMultipleObjects () to wait for a semaphore. When the synchronization task is completed, the thread applies releasesemaphore () to release the semaphore:
BOOL ReleaseSemaphore (HANDLE hsema, LONG lreleasecount, Lplong lpprevious);
12. User interface threads are created:
When you create a user interface thread, you must first derive the class from CWinThread. This class must be declared and implemented using DECLARE_DYNCREATE and implement_dyncreat macros. User interface threads are typically used to process user input and respond to user events.
13. Creation and termination of processes;
Call the CreateProcess function to create a new process that runs the specified program. The prototype of CreateProcess is as follows:
BOOL CreateProcess (
LPCTSTR Lpapplicationname,
LPTSTR lpCommandLine,
Lpsecurity_attributes Lpprocessattributes,
Lpsecurity_attributes Lpthreadattributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID Lpenvironment,
LPCTSTR Lpcurrentdirectory,
Lpstartupinfo Lpstartupinfo,
Lpprocess_information lpprocessinformation
);
which
Lpapplicationname points to the string that contains the name of the module to run.
lpCommandLine points to the command-line string.
Lpprocessattributes describes the security properties of the process, which is useful under NT.
Lpthreadattributes describes the security properties of the process's initial thread (the main thread), which is useful under NT.
bInheritHandles indicates whether the child process (the process being created) can inherit a handle to the parent process. The handle that can be inherited is a thread handle, a named or unnamed pipe, a mutex object, an event, a semaphore, an image file, a normal file and a communication port, and so on; some handles cannot be inherited, such as memory handles, DLL instance handles, GDI handles, urer handles, and so on.
A handle inherited by a child process is passed to it by the parent process through the command line or interprocess communication (IPC) mode by the parent process.
dwCreationFlags represents the priority category of the creation process and the type of process. The type of process is created, such as the console process, debugging process, etc., and the priority category is used to control the priority level of the process, divided into four categories: idle, Normal, High, real_time.
Lpenviroment points to the environment variable block, environment variables can be inherited by the quilt process.
Lpcurrentdirectory points to a string that represents the current directory, which can be inherited.
Lpstartupinfo points to the STARTUPINFO structure, controlling how the main window of the process appears.
Lpprocessinformation points to the process_information structure, which stores the returned process information.
From its parameters, you can see what information you need to specify to create a new process.
As you can see from the above explanation, a process contains a lot of information. Returns a pointer to a process information structure type if the process was created successfully. The process information structure is as follows:
typedef struct _PROCESS_INFORMATION {
HANDLE hprocess;
HANDLE Hthread;
DWORD Dwprocessid;
DWORD dwThreadID;
}process_information;
The process information structure includes the process handle, the main thread handle, the process ID, and the main thread ID.
Termination of the process
The process terminates under the following conditions:
Call ExitProcess to end the process;
The main thread of the process returns, implicitly calling ExitProcess causes the process to end;
The last thread of the process terminates;
Call TerminateProcess to terminate the process.
When you want to end a process, you send a WM_QUIT message to the main window, and of course you can call ExitProcess from any of its threads.