Thread synchronization mechanisms include critical section, mutex, semaphore advantages and disadvantages

Source: Internet
Author: User

Thread Synchronization Technology.
1. critical sections (critical segment). If there is a part in the source code that cannot be executed simultaneously by two or more threads, you can use the critical segment to serialize the code. It can only be used in an independent process or an independent application. The usage is as follows:
// Create a form
Initializecriticalsection (critical1)
// Destroy the form
Deletecriticalsection (critical1)
// Thread
Entercriticalsection (critical1)
...... Protected code
Leavecriticalsection (critical1)
2. mutex (mutex object) is a global object used for serializing access to resources. We first set the mutex object, then access the resource, and finally release the mutex object. When a mutex object is set, if another thread (or process) tries to set the same mutex object, the thread will stop until the previous thread (or process) releases the mutex object. Note that it can be shared by different applications. The usage is as follows:
// Create a form
Hmutex: = createmutex (nil, false, nil)
// Destroy the form
Closehandle (hmutex)
// Thread
Waitforsingleobject (hmutex, infinite)
...... Protected code
Releasemutex (hmutex)
3. semaphore (semaphore), which is similar to a mutex, but can be counted. For example, a given resource can be simultaneously accessed by three threads. In fact, mutex is the semaphore with the largest count. The usage is as follows:
// Create a form
Hsemaphore: = createsemaphore (nil, linitialcount, lmaximumcount, lpname)
// Destroy the form
Closehandle (hsemaphore)
// Thread
Waitforsingleobject (hsemaphore, infinite)
...... Protected 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.