Principle Analysis:
A mutex is a system kernel object that each thread can own, and who owns it can execute
After execution, use the ReleaseMutex function to release ownership so that other waiting threads can use the
Other threads can queue up with the WaitForSingleObject function (waiting can also be understood as queued requests)
Use procedure
var hmutex:thandle; {You should first declare a global mutex handle} CreateMutex {Create mutex}waitforsingleobject {wait function queued}releasemutex {release ownership}closehandle {last release Mutex}
The parameters of the ReleaseMutex and CloseHandle are the handles returned by the CreateMutex, and the key is the CreateMutex function
function CreateMutex ( lpmutexattributes:psecurityattributes; Binitialowner:bool; {Whether to have the creator (the main thread in this case) have the mutex} Lpname:pwidechar {The mutex can be given a name, if not the name can be assigned to nil}): Thandle;
1, the first parameter said before
2, the second parameter here must be False, if the main thread has mutual exclusion, theoretically, and so on, the program exits after the other threads have the opportunity
When the value is false, the first thread that executes will have the mutex first, and once the other threads are owned, the first one must wait.
3, the third argument, if given a name, the function will look from the system to see if there is a mutex object with the same name, and if so, return a handle to the object
If the assignment is nil, a new mutex will be created directly, and the next example will have a name
of this example
The code is as follows
Delphi multithreaded Programming (10)-Multi-threaded synchronization mutex (mutex object)