Windows Thread Synchronization and mutex technology excerpt 1

Source: Internet
Author: User
1.1 Thread Synchronization Overview

Without the ability to synchronize objects and operating systems to monitor special events, threads may be forced to use technologies with side effects to synchronize themselves with special events. Without the thread synchronization technology supported by the operating system, many problems may occur, such as unnecessary allocation.CPUTime, waste; among high and low priority threads, if the Low thread is responsible for the signal reset task, it may never be able to perform the reset.

 

1.2 Critical Section 1.2.1 Overview

Critical section:Among all synchronization objects, the critical section is the easiest to use, but itIt can only be used to synchronize threads in a single process. Only one thread can access a data zone at a time in the critical section. Also, among these synchronization objects, onlyThe critical section is not a kernel object.Is not managed by low-level components of the operating system, andHandle cannot be used to manipulate.

 

1.Create a critical section in the process, that is, assignCritical_sectionData structure. The allocation of the structure of the critical section must be global, so that different threads of the process can access it.

2.You must callInitializecriticalsectionTo initialize the critical section. Before releasing a resource, you only need to initialize it once.

3.Void entercriticalsection: Blocking function.The function returns when the calling thread is granted ownership. In other words, when the calling thread cannot obtain the ownership of the specified critical section, the thread will sleep and will not be allocated to it before it is awakened.CPU.

4.Execute tasks in the critical section

5.Bool leavecriticalsection: Non-blocking function. Subtract one from the reference count of the current thread for the specified critical section. When the count is set to zero, the other thread waits for the reference count of this critical section.OneThe thread will be awakened.

6.When you do not need to use this critical section, useDeletecriticalsectionTo release the resources required for the critical section. This function can no longer be used after executionEntercriticalsectionAndLeavecriticalsectionUnless you useInitializecriticalsectionThe critical section is initialized.

 

 

1.2.2 Note:

1.Only one thread is allowed to access the critical area at a time. Each thread must call the critical area mark (that is, oneCritical_sectionGlobal variable)EntercriticalsectionOther threads that want to gain access will be put in sleep state, and before being awakened, the system will stop allocating themCPUTime slice. In other words,The critical section can be owned by only one thread.Of course, there is no thread to callEntercriticalsectionOrTryentercriticalsectionThe critical section does not belong to any thread.

2.When a thread with the critical zone ownership callsLeavecriticalsectionWhen giving up ownership, the system only wakes up one thread in the waiting state and gives it ownership. Other threads continue to sleep.

3.Note,The thread that owns the critical section.EntercriticalsectionThe call will be successful (this means that repeated calls will return immediately), and the critical section mark (that is,Critical_sectionGlobal variable) add one to the reference count. Before another thread can have this critical section, the thread that owns it must callLeavecriticalsectionAfter the reference count is reduced to zero many times, another thread may have this critical section. In other words, in a thread that normally uses the critical section,CalsectionAndLeavecriticalsectionIt should be used in pairs.

4. Tryentercriticalsection
Bool tryentercriticalsection (
Lpcritical_sectionLpcriticalsection
);
We can see from the function declaration, Entercriticalsection The Return Value of the function is Void And here is Bool . Visible Tryentercriticalsection You need to determine the return value. Before calling Tryentercriticalsection If the specified critical section is not owned by any thread (or no calling thread), this function gives the access to the called thread and returns True However, if the critical section is already owned by another thread, it immediately returns False Value. Tryentercriticalsection And Entercriticalsection The biggest difference between them is that Tryentercriticalsection Never suspends a thread.

1.3 Use a kernel object to synchronize threads 1.3.1 Overview

Critical zones are ideal for serializing access to data in a process because they are fast. But we may want to make some applicationsProgramIt is synchronized with other special events in the computer or operations executed in other processes. At this time, the critical section is powerless. You need to use the kernel object for synchronization.

 

The following kernel objects can be used to synchronize threads:

1.Process,Processes

2.Thread,Threads

3.File,Files

4.Console input,Console input

5.File Change Notification,File Change specifications

6.Mutex,Mutexes

7.Semaphores,Semaphores

8.Events (automatic resetting events and manual resetting events ),Events

9.An equable timer (only usedWindow NT4Or higher ),Waitable timers

10.Jobs

 

Each of the above objects can be in one of two States (Signaled) And no signal (Nonsignaled). For example, when processes and threads terminate, their kernel objects become signal-free, while they are in the creation and running status.

 

1.3.2 Kernel Object synchronization Application

1.When a thread obtains the kernel object handle of a process, it can: change the process priority, obtain the exit code of the process, and synchronize the thread with the end of a process.

2.When obtaining the kernel object handle of a thread, it can: Change the running state of the thread, synchronize with the end of the thread, and so on.

3.When obtaining the file handle, this thread can alsoI/OOperations are synchronized.

4.The console input object can be used to wake the thread up when the input enters to execute related tasks.

5.Other kernel objects-file change notifications, mutex volumes, semaphores, events, and other timers-only exist to synchronize objects. Correspondingly, there are alsoWin32Function to create, open, and close these objects, and synchronize threads with these objects. No other operations can be performed on these objects.

 

1.3.3 Unique features of mutex (experiment in the Appendix)

The difference between a mutex object and all other kernel objects is that it is owned by a thread.All of its synchronization objects have either signal or no signal. In addition to recording the current signal status, the mutex object must remember that the thread owns it at this time. If a thread is terminated after obtaining a mutex object (that is, it is set to a non-signal state), the mutex will be discarded. In this case, the mutex will always remain in the non-signal state, because no other thread can callReleasemutexTo release it.

When the system finds this situation, the mutex is automatically set back to the signal state. Other threads waiting for the semaphore will be awakened, but the return value of the function isWait_abandonedInstead of normalWait_object_0. At this time, other threads can know whether the mutex is released normally.

others, the mutex quantity is similar to critical_section . For a thread with the mutex, waitforsingleobject is returned immediately, but the Count of mutex usage increases, similarly, you must call releasemutex multiple times to change the reference count to zero for other threads to use.

Related Article

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.