Thread Synchronization for beginners

Source: Internet
Author: User

In a multi-threaded environment, each thread has its own local thread stack and register. This value may be incorrect if multiple threads can read and write the same resource. For example, when two threads read and write the same data, the data will be discarded. In this case, we want to lock the object access permission. There are two statuses for thread synchronization: signaled and non-signaled.

The signaled status allows the object to access and modify data.

The non-signaled state does not allow data to be acquired or modified on a local stack of a thread.

Many thread synchronization methods can be used in multi-thread synchronization. The following method is used to synchronize two objects.

Thread synchronization on different processes:

Event:
Event is a thread synchronization object used to set the signaled or non-signaled status. The signaled status can be set manually or automatically, depending on the definition during event creation.

Mutex:
Mutex is a thread synchronization object that allows only one thread to access resources for a period of time. Other resources are allowed to be accessed only when a process enters the signaled state.

Semaphore:
Semaphore is a thread synchronization object that allows zero or any number of threads to synchronously access resources.
Perform on-site synchronization in the same process:
Thread Synchronization in same process:
Critical Section
The critical section is a thread synchronization object. Other thread objects such as semaphore, event, and mutexsemaphore are used to synchronize resources in different processes. However, the critical section allows synchronization in a unified process.
The above differences are the main differences between the thread synchronization objects. Other differences are described below:

Win32 wait function:

The wait family of functions are used to wait the thread synchronization object while a process completes. the widely used functions are waitforsingleobject and waitformultipleobjects functions. The waitforsingleobject function is used for waiting on a single
Thread synchronization object. This is signaled when the object is set to signal or the time out interval is finished. If the time interval is infinite, it waits infinitely.

The waitformultipleobjects is used to wait for multiple objects signaled. in the semaphore thread synchronization object, when the counters go to zero the object is non-signaled. the auto reset event and mutex is non-signaled when it releases the object. the
Manual reset event does affect the wait functions 'State.
MFC lock/unlock Resource:

The MFC cmutex, ccriticalsection, csemaphore, and cevent classes are used to synchronize the threads in Microsoft Foundation Class Library.

The csinglelock and cmultilock are used to control the access to the resources in multithread programming. the csinglelock and cmultilock classes have no base class. csinglelock is used to lock the single synchronization object at a time. cmultilock is used
To control more than one thread synchronization objects with a special time interval. The csinglelock/cmultilock lock and unlock member functions are used to the lock or release the resource.

The entity and cmultilock constructors use the entity object for locking and unlocking the resource. All the thread synchronization classes are derived from csyncobject base class. So, the constructor has any one of the thread synchronization classes
Derived from csyncobject. csinglelock islocked member is use to find if the object is locked already or not.

The cmultilock class is used to control the access to the resources in multiple objects. the cmultilock constructor has an array of csyncobject objects and the total number of counts in the thread synchronization classes. the islocked member function is used
To check the participating synchronization object state.
Thread synchronization objects:
Critical section:

The critical section object is same as the mutex object. but, the mutex object allows synchronizing objects processing ss the process. but the critical section object does not allow synchronization with different processes. the critical section is used to synchronize
The threads within the process boundary.

It is possible to use mutex instead of critical section. But, the critical section thread contains object is slightly faster compared to other synchronization objects. The critical section object contains threads within the process. Critical Section
Allows accessing only one thread at a time.
Win32 critical section object:

The process allocates memory for the critical section using the critical_section structure. The critical section structure declared in the WINNT. H is as follows:
Typedef struct _ rtl_critical_section {
Prtl_critical_section_debug debuginfo;
// The following three fields Control entering
// And exiting the critical section for the resource
Long lockcount;
Long recursioncount;
Handle owningthread; // from the thread's clientid-> uniquethread
Handle locksemaphore;
DWORD spincount;
} Rtl_critical_section, * prtl_critical_section;

In critical section, we allocate memory for critical_section structure and initializes the critical section. The iniailizecriticalsection and sections are used to initialize the critical section. If we initialize the critical section,
Then only, we use any one of the entercriticalsection, tryentercriticalsection, or other functions. The entercriticalsection function is used enter the critical section, and tryentercriticalsection to enter the critical section without blocking.
Leavecricalsection is used to leave the critical section.

If any of the other synchronization object names is same as critical section object, the critical section object waits for the ownership infinitely. the critical section object does not allow moving or copying the object. if we have to synchronize the thread
On different processes, use mutex object. deletecriticalsection function releases all the critical section objects. after calling the deletecriticalsection, it is not possible to call entercriticalsection or leavecriticalsection.
Example:
Critical_section m_cs;

// Initilize the critical section
Initializecriticalsection (& m_cs );

The two threads try to access the same variable. The global variable g_n tries to access two threads. The Global m_cs critical_section structure is used to synchronize the two threads.
Uint threadone (lpvoid lparam)
{
//
// Lock the critical section
Entercriticalsection (& m_cs );

// Some process

// Release the critical section
Leavecriticalsection (& m_cs );

Return 0;
}

Thread two:
Uint threadtwo (lpvoid lparam)
{
// Lock the critical section
Entercriticalsection (& m_cs );

// Some process

// Release the critical section
Leavecriticalsection (& m_cs );

// Return the thread
Return 0;
}
MFC critical section object:

The ccriticalsection class provides the functionality of critical section synchronization object. The default constructor is used to construct the critical section object. The lock and unlock functions are used to control the resource access in the synchronization
Object.

The critical_section's m_sect data member allows initializing the critical_section structure. the lock function overloaded in two forms. the lock function without any arguments is used to lock the resource. the other form of lock function needs the number
Milliseconds to wait. All the critical section members are declared in afxmt. INL file as inline functions.
Example:
// Global critical section
Ccriticalsection c_s;
Int g_c;

//// // Thread one //////////////////// ///

Uint threadfunction1 (lpvoid lparam)
{

// Create object for single lock
Csinglelock lock (& c_s );

// Lock
Lock. Lock ();

// Process

// Unlock
Lock. Unlock ();

// Return
Return 0;
}

/// // Thraed 2 ////////////////////
Uint threadfunction2 (lpvoid lparam)
{

// Single lock constract critical section
Csinglelock lock (& c_s );

// Lock
Lock. Lock ();

// Process

// Unlock
Lock. Unlock ();

// Return
Return 0;
}
Event:

Event is the thread synchronization object to set signaled state or non-signaled state. The event has two types. They are manual reset event and auto reset event.

The manual event has signaled user set to non-signaled state, uses resetevent function manually. the auto reset event automatically occurs when the object is raised to the non-signaled state. the event thread synchronization object is used to synchronize
Particle event entered in the thread. The event object is used to set the operating system kernel flag in the thread.
Win32 event object:

The createevent function is used to create the event thread synchronization object. The manual or auto reset event choice is mentioned at the createevent function parameter initialization. The wait family functions (waitforsingleobject, waitformultipleobjects)
Are use to wait when a participating event occurs. The group of objects waits for the events: the single object signaled or the entire events are signaled in the thread.

Createevent function is used to create manual or auto reset events. this function is used to create named and unnamed event objects. setevent function is used to set the event object to signal state. the resetevent function is used to set the event object
Non-signaled state. if the function is successful, it returns the handle of that event. if the named event is already available, the getlasterror function returns the error_already_exists flag. if the named event is already available, the openevent Function
Is used to access the event previusly created by the createevent function.
Example:
// Handle for event
Handle g_event;
// Create a manual-Reset event object with no security attributes

G_event = createevent (null, true, true, "Event ");

Resetevent (g_event );

// Do Process

Setevent (g_event );
MFC event object:

Event is useful for waiting if something happens (or an event occurs ). cevent class is used for event object functionality. the cevent class is derived from the abstract csyncobject class. the csyncobject is derived from the cobject mother class. the csinglelock
Or cmultilock constructor use one of the csyncobject Derived classes. The cevent constructor specifies the manual or auto reset event options.

MFC cevent class provides the constructor with default arguments. if we want to control our needs, we set the ownership for the event object, manual or auto reset event flag, the name of the event object (if named event ), and the security attributes. if
Name matches with that of an existing event object, check the type of the object. if that object is an event, the cevent constructor simply replies the handle of the previous event. if the name exists for any of the other synchronization object, the cevent
Constructor gives an error message.

The manual event object signaled/non-signaled uses setevent or resetevent function. the auto reset event occurs when it releases any one of threads in the event object. we don't use csyncobject directly. because, the csyncobject is an abstract base class. all
The event members are declared in the afxmt. INL file as inline functions.
Mutex synchronization object:

Mutex is the synchronization object used to synchronize the threads with more than one process. The mutex is as the name tells, mutually exclusive. The mutex object allows accessing the resource single thread at a time.
Win32 mutex object:

The createmutex function is used to create the mutex object. In the createmutex function, we initialize the named mutex or unnamed mutex, and set the ownership to true or false arguments.

If we create two-named mutex using createmutex function within the same process, the second createmutex function returns error. if we create two or more mutex objects on different processes, with the same name, when we call first time, The createmutex Function
Creates the mutex. The other createmutex function returns the handle of the previous mutex object.

The openmutex function is used to open an existing mutex using the supplied mutex name. the releasemutex is used to release a mutex object. the threads wait in first out order for taking the ownership for the waiting threads. if we try to take
Ownership twice, deadlock occurs. We the call releasemutex, and then try to take the ownership.
Example
Handle g_mutex;
DWORD dwwaitresult;

// Create a mutex with initial owner.
G_mutex = createmutex (null, true, "mutextoprotectdatabase ");

// Wait for ownership
Dwwaitresult = waitforsingleobject (g_mutex, 5000l );

// Check takes ownership

// Release mutex
Releasemutex (g_mutex ))
MFC mutex object:

The MFC cmutex class is used to control the mutex objects. the cmutex constructor has three parameters. we can specify the name of the mutex as a parameter. if this is null, an unnamed mutex is created. the security attributes are used to set the security attributes
For the mutex object. If the name already exists for a mutex object, the constructor simply returns the existing mutex object. If the name exists for some object, the constructor fails.

To control resource access for single mutex object, use csinglelock class. If you want to control multiple mutex objects, the cmultilock is used to control the access to resources in multithreaded programming.
// Global mutex object
Cmutex G_m;
Int g_c;

Uint threadfunction1 (lpvoid lparam)
{

// Create object for single lock
Csinglelock lock (& G_m );

Lock. Lock ();

// Process

Lock. Unlock ();

// Return
Return 0;
}

Uint threadfunction2 (lpvoid lparam)
{

// Single lock construct mutex
Csinglelock lock (& G_m );

Lock. Lock ();

// Process

Lock. Unlock ();

// Return
Return 0;
}
Semaphore thread synchronization object:

Semaphore is a thread synchronization object that allows accessing the resource for a count between zero and maximum number of threads. if the thread enters the semaphore, the count is incremented. if the thread completed the work and is removed from the thread
Queue, the count is decremented. When the thread count goes to zero, the synchronization object is non-signaled. Otherwise, the thread is signaled.
Win32 semaphore synchronization object:

The createsemaphore function is used to create a named or unnamed semaphore thread synchronization object. the initial count and maximum count is mentioned in the createsemaphore function. the count is never negative and less then the Total Count value. the
Waitforsingleobject waits for more than one object in semaphore object.

The waitformultipleobjects function is non-signaled when all the objects are returned. the opensemaphore function is used to open an existing handle to a semaphore object created within the process or another process. the releasesemaphore function is used
Release the semaphore from the thread named queue. If the createsemaphore function has created the same named thread synchronization object within the process, the specified returns 0. The getlasterror function is used to retrieve the reason
For the failure.
Example:
Handle g_semaphore;

// Create a semaphore with initial and Max.
G_semaphore = createsemaphore (null, 4, 4, null );

DWORD dwwaitresult;
// Take Ownership
Dwwaitresult = waitforsingleobject (g_semaphore, 0l );

// Check the ownership

// Release semaphore
Releasesemaphore (g_semaphore, 1, null );
MFC semaphore synchronization object:

The csemaphore class allows us to create the csemaphore object. The csemaphore class is derived from the abstract csyncobject base class. The csemaphore class constructor is used to specify the count and maximum number of resource access.

The virtual destructor is used to delete the csemaphore class object without affecting the csyncobject base class. The unlock function is used to unlock the resources.
Conclusion:

Thread Synchronization is used to access the shared resources in a Multithread environment. The programmer decides the situation for when to use the synchronization object syntax. The MFC thread synchronization classes internally call the Win32 API functions.
The MFC thread synchronization classes wrap specification of the functionalities form the Windows environment.

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.