Thread synchronization of Kernel objects

Source: Internet
Author: User
Tags apc filetime mutex semaphore

Objective:

The specific kernel objects that can be waited for are:

Process, thread, job, file and console standard input stream/output stream/error stream, event, waiting timer, semaphore, mutex.

Wait function:

DWORD WaitForSingleObject (    HANDLE hobject,// used to identify the kernel object to wait for    DWORD dwmilliseconds) ; // Time to wait DWORD WaitForMultipleObjects (    DWORD dwcount,// function checks the number of kernel objects (max. maximum_wait_objects)     CONST handle* phobjects,// array for a kernel object handle    BOOL bwaitall,//  Whether to wait for all objects to trigger a    DWORD dwmilliseconds); // Wait Time

Side effects of waiting for success: (Windows core programming)

When the wait function discovers that the object has been triggered, it is called a successful call, and when called, the state of the object changes, which is called a side effect caused by waiting for success.

Body:

1. Events Kernel Object (event)

The event contains a reference count, a Boolean value that indicates whether the event is an automatic reset event or a manual reset event, and another Boolean value that indicates that the event has not been triggered.

HANDLE CreateEvent (psecurity_attributes PSA, BOOL bmanualreset,//true indicates manual reset, false for automatic resetBOOL Binitialstate,//true indicates a trigger state, false indicates no state was triggeredpctstr pszname); HANDLE Createeventex (psecurity_attributes PSA, Pctstr pszname, DWORD dwFlags,//Create_event_initial_set set is initialized to the trigger state//, Create_event_manual_reset is set to create a manual reset eventDWORD dwdesiredaccess);//specifies how the handle returned when the event was created has access to the eventHANDLE openevent (DWORD dwdesiredaccess, BOOL Binherit, Pctstr pszname); BOOL SetEvent (HANDLE hevent);//Triggering EventsBOOL resetevent (HANDLE hevent);//set event to not trigger stateBOOL PulseEvent (HANDLE hevent);//immediate recovery to the non-triggered state after triggering the event first

When a manual reset event is triggered, all threads that are waiting for the event become scheduled. When an auto-reset event is triggered, only one thread that is waiting for the event becomes a scheduled state.

2. Waiting Timer Kernel object (waitable timer)

It can be triggered at a specified time, or once every time.

 handle createwaitabletimer (psecurity_attributes PSA, BOOL bmanualreset, Pctstr Pszname); HANDLE Openwaitabletimer (DWORD dwdesiredaccess, BOOL binherithandle, Pctstr pszname);  BOOL SetWaitableTimer (HANDLE htimer,  const  large_integer* Pduetime,//  long Lperiod,//  After the first trigger, the timer should trigger at what frequency  ptimerapcroutine Pfncompletionroutine,// APC  PVOID Pvargtocompletionroutine,// APC parameter   BOOL Bresume); BOOL Cancelwaitabletimer (HANDLE htimer);  //  cancels the timer  

The Pduetime parameter that is set to wait for the timer is large_integer* type, and the time of the SystemTime type is used to convert the SystemTimeToFileTime () to the bit filetime, The members of the FILETIME are then copied to the Large_integer struct member, and then the Large_integer address is passed to Pduetime.

3. Semaphore kernel Object (Semaphore)

Contains a usage count, a maximum resource count, and a current resource count.

The following rules apply to the semaphore:

1 if the current resource count is greater than 0, then the semaphore is in a triggered state;

2 if the current resource count equals 0, then the semaphore is in the non-triggering state;

3 The system will never make the current resource count negative

4 The current resource count will never be greater than the maximum resource count

HANDLE createsemaphore (    psecurity_attribute PSA,    long lInitialCount,    long lMaximumCount,    Pctstr pszname); HANDLE Createsemaphoreex (    psecurity_attributes PSA,    long lInitialCount,    long lmaximumcount,    pctstr Pszname,    DWORD dwFlags,// set to 0, system reserved    DWORD dwdesiredaccess);

BOOL ReleaseSemaphore (
HANDLE Hsemaphore,
LONG lReleaseCount,
Plong plpreviouscount);//Increment the current resource count of the semaphore

semaphores perform test and setup operations atomically, and when we request a resource for a semaphore, the operating system checks to see if the resource is available and decrements the amount of resources available, and the entire process is not interrupted by another thread.

4. Mutex kernel object (mutex)

A mutex object contains a usage count, a thread ID, and a recursive count. The thread ID is used to identify which thread in the system is currently occupying this mutex, and the recursive count indicates the number of times that the thread occupies that mutex.

Usage rules for mutexes:

1 if the thread ID is 0 (invalid), then the mutex is not occupied by any thread, and he is in a triggered state.

2 If the thread ID is a non-0 value, then one thread has already occupied the mutex, and he is not in the triggered state

3 Unlike all other kernel objects, the operating system has special handling of mutexes, allowing them to violate some regular rules (say below)

HANDLE CreateMutex (    psecurity_attributes pas,    BOOL binitialowner,// control the initial state of the mutex, If you pass false,
Then the thread ID and recursive count of the mutex object will be set to 0 (the trigger state).
Pass True, the thread ID is the thread ID of the calling thread, and the recursive count will be set to 1 (not triggering state) pctstr pszname); HANDLE Createmutexex ( psecurity_attributes PSA, pctstr Pszname, DWORD DwFlags, DWORD dwDesiredAccess); HANDLE OpenMutex ( DWORD dwdesiredaccess, BOOL binherithandle, pctstr pszname); BOOL ReleaseMutex (HANDLE hmutex); // release mutex, recursive count minus 1

How to use:

To gain access to the protected resource, the thread calls a handle that waits for the function and passes in the mutex. Internally, the wait function checks to see if the thread ID is 0. If 0, then the function sets the thread ID to the thread ID of the calling thread, sets the recursive count to 1, and then lets the calling thread continue to run. (equivalent to the critical segment of EnterCriticalSection ()).

If the wait function detects that the thread ID is not 0, the calling thread enters the wait state. When another thread sets the thread ID of the mutex to 0, the system remembers that a thread is waiting, so it sets the thread ID to the thread ID of the thread that is waiting, sets the recursive count to 1, and the waiting thread becomes a scheduled state.

All of the mutex mentioned above is the same as other kernel objects, but the mutex has its own features:

The above-mentioned violation of the general rule is: If the wait function detects that the thread ID is not 0, but the thread ID of the current calling thread is equal, then the system will keep the thread in a scheduled state-even if the mutex has not been triggered, then the recursive count plus 1, the only way to make the recursive count greater than 1 is to take advantage Let the thread wait for the same mutex multiple times.

When the mutex is released, ReleaseMutex also checks that the thread ID of the calling thread is consistent with the thread ID inside the mutex, and if it is consistent, the recursive count is decremented, and if it is not the same, false is returned, and the call to GetLastError returns Error_not_owner.

More wait functions:

//wait for the process identified by the hprocess until the thread that created the first window of the application has no pending input. DWORD WaitForInputIdle (HANDLE hprocess, DWORD dwmilliseconds);//not only is the kernel object triggered, it is time for the calling thread to become a scheduled state, and when the window information needs to be dispatched to a//when windows are created by the calling thread, they also become a scheduled state. DWORD MsgWaitForMultipleObjects (DWORD dwcount, Phandle phobjects, BOOL bWaitAll, DWORD dwmilliseconds,    DWORD dwwakemask);D Word msgwaitformultipleobjectsex (DWORD dwcount, Phandle Phobjects, DWORD dwmilliseconds, DWORD Dwwakemask, DWORD dwFlags); BOOL waitfordebugevent (Pdebug_event Pde, DWORD dwmilliseconds);//atomic operation to trigger a kernel object and wait for another kernel objectDWORD signalobjectandwait (HANDLE hobjecttosignal,//can only be mutex, event, Semaphore kernel objectHANDLE Hobjecttowaiton,//a waiting kernel object can beDWORD dwmilliseconds, BOOL balertable);

Thread synchronization of Kernel objects

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.