Audio/Video Synchronization series-Windows synchronization mechanism

Source: Internet
Author: User

Synchronization means to ensure that a program is not faulty when it is not properly switched.

For window3.1, although there are multiple tasks, there is no synchronization grassroots. Because the collaboration between these multitasking tasks is achieved by Calling API functions, such as getmessage and peekmessage. If a program calls getmessage or peekmessage, it means that I am in an interrupted state.

Win32 programs do not have such collaborative multitasking, so they must be ready to be switched off by the CPU at any time. A real Win32 program should not exhaust its CPU time to wait for something to happen.

WIN32API has four main synchronization objects: (1) event; (2) semaphore; (3) mutexes mutex; (4) critical section.

In addition to the critical setion, the rest are global objects of the system and work with different processes and threads in the same process. In this way, the synchronization mechanism can also be used for process synchronization.

1. Event)

This is a type of synchronization object. as its name implies, some special activities occur in another process or thread around this center. When you want the thread to temporarily suspend, it does not consume the CPU cycle. Events are similar to common message concepts. If we analyze the message kernel, we can certainly find that it is implemented by events. Here we will explain the differences between events and messages:

An event is actually the arrival of a message. That is to say, when a message arrives after a series of processes, it will trigger an event processor and the event processor will call the event processing function you wrote. A message is sent to the system, and the system has a message queue. Then, based on certain scheduling conditions, the system will obtain the messages waiting for processing (of course, they may be lost) and call the corresponding message function. Although the results are the same, the event system is obviously secure because messages are not lost.

The program can use createevent or openevent to obtain a handle for the event:

Handle createevent(
Lpsecurity_attributes
Lpeventattributes,// SD
Bool Bmanualreset,// Reset type
Bool Binitialstate,// Initial state
Lpctstr Lpname// Object Name
);

 

Handle openevent (
DWORD
Dwdesiredaccess,// Access
Bool Binherithandle,// Inheritance Option
Lpctstr Lpname// Object Name
);

For more information about function parameters and return values, see msdn.

 

Then, the program calls waitforsingleobject and selects the event handle and wait timeout time. Then the thread will be suspended until other threads call the following API function and receive event-related signals before being activated again.

Bool setevent (
Handle
Hevent// Handle to event

);

 

Bool pulseevent (
Handle
Hevent// Handle to event object
);

For example, if a thread wants to use the sorting result of another thread, you may want to use an event. The worst way is to execute this thread and set the global variable flag at the end. The other thread checks whether this flag has been set cyclically, which wastes a lot of CPU time. It is easy to use events to do the same thing. The sorting thread generates an event at the end, and other threads call waitforsingleobject. This causes the thread to be suspended. When the sorting thread is complete, call setevent to wake up another thread for further execution.

Besides waitforsingleobject, waitformultipleobjects allows a thread to be suspended until multiple event conditions are met.

Examples.

During audio/video communication, we use a TCP socket, m_hdatasock to receive data. When no data arrives, the receiving thread will be suspended until data arrives or the socket times out to process the data, the sample method is as follows:

Uint recvdatathread (lpvoid ppara)
{
Wsaevent = wsacreateevent ();
Wsaeventselect (m_hdatasock, m_hevent, fd_read | fd_close );
While (! M_bthreadend)
{
DWORD dwwait = wsawaitformultipleevents (1, & m_hevent, false, 18000, false );
If (wsa_wait_timeout = dwwait)
{
// Timeout Processing
Break;
}
If (wait_object_0 = dwwait)
{
Wsanetworkevents netevents;
If (socket_error = wsaenumnetworkevents (m_hdatasock, m_hevent, & netevents ))
{
Continue;
}
If (netevents. lnetworkevents & fd_read) & (0 = netevents. ierrorcode [fd_read_bit])
{
// Receive data
}
Else if (netevents. lnetworkevents & fd_close)
{
// The processing channel is disabled.

Break;
}
}
}
Wsacloseevent (m_hevent );
_ Endthreadex (0 );
Return 0;
}

2. Semaphores

Semaphores is useful when you need to restrict access to special resources or restrict a piece of code to some threads. For example, there are ten resources in the same way. When you need them, they are already occupied by ten others. In this way, you have to wait until someone does not need it and the resources are returned.

In Win32 programming, getting semaphores is like getting a control of this resource.

To use semaphores, a thread calls createsemaphore to obtain a handle for semaphores. That is, bind semaphores to the resource, initialize the semaphores, and return the handle of the semaphores.

The function prototype is as follows:

Handle createsemaphore (
Lpsecurity_attributes
Lw.maphoreattributes,// SD
Long Linitialcount,// Initial count
Long Lmaximumcount,// Maximum count
Lpctstr Lpname// Object Name
);

 If semaphores is created in another process, you can use opensemaphore to obtain its handle.

Handle opensemaphore (
DWORD
Dwdesiredaccess,// Access
Bool Binherithandle,// Inheritance Option
Lpctstr Lpname// Object Name
);

The next step is to use the wait function to block the thread. If the semaphore count is greater than 0, the waiting function simply processes the number of semaphores used and the thread continues to execute. In other words, if the number of semaphores exceeds the maximum value, the waiting thread is suspended. You can also use releasesemaphore to release resources.

Bool releasesemaphore (
Handle
Hsemaphore,// Handle to semaphore
Long Lreleasecount,// Count increment amount
Lplong Lppreviouscount// Previous count
);

That is, the semaphore object is used to manage the allocation and recovery of a resource.

3. Mutexes)

Mutex is the abbreviation of "mutual exclusion. It is expected that only one thread can access one resource or code at a time. The usage is similar to that of semaphores. The function prototype for creating and releasing mutex is as follows:

Handle createmutex (
Lpsecurity_attributes
Lpmutexattributes,// SD
Bool Binitialowner,// Initial owner
Lpctstr Lpname// Object Name
);

Bool releasemutex (
Handle
Hmutex// Handle to mutex
);

You can encapsulate the method into a class as follows:

Class cmutex
{
Public:
Cmutex (handle hmutex) {m_hmutex = hmutex; waitforsingleobject (m_hmutex, infinite );}
Virtual ~ Cmutex () {releasemutex (m_hmutex );}
PRIVATE:
Handle m_hmutex;
};

Declare a handle m_hmutex when using it. Call the interface to create a mutex, m_hmutex = createmutex (null, false, null ); then, you can construct such a class before any code that requires mutual exclusion. For example, cmutex mutex (m_hmutex );

 

4. Critical Section)

The critical segment is equivalent to a micro-mutex and can only be used by threads in the same process. The critical section is used to prevent multiple threads from executing a piece of code at the same time. Compared with other synchronization machines, the critical zone is relatively simple and easy to use. Generally, a global variable of the critical_section type is declared first, and then the following three functions are called to use it.

Void initializecriticalsection (
Lpcritical_section
Lpcriticalsection// Critical section
);

 

Void entercriticalsection (
Lpcritical_section
Lpcriticalsection// Critical section
);

 

Void leavecriticalsection (
Lpcritical_section
Lpcriticalsection// Critical section
);

5. Waitforsingleobject/waitformultipleobjects Function

In fact, in addition to the above four methods, you can also use the waitforsingleobject/waitformultipleobjects function. The waiting handle can be a thread handle or a file handle.

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.