Delphi multithreaded Programming (10)-Multi-threaded synchronization mutex (mutex object)

Source: Internet
Author: User

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)

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.