[Win32 Basics] thread synchronization Overview

Source: Internet
Author: User

Thread: Synchronize objects in some cases.

Basic Principles

The thread synchronization mechanism is designed for the collaboration of various threads. Synchronization is the only way to ensure the persistence of shared data.

In the synchronization process, the two most important concepts are synchronization objects (Mutex, Semaphore, Event, CriticalSection) And wait function ((WaitForSingleObject (),WaitForMultipleObjects ()). The synchronization object is a variable in the memory. You can access it as you access normal data.

During thread synchronization, a synchronization object needs to be defined first. The synchronization object generally has two states: flag (set bit, signaled) and unsignaled (unsignaled, nonsignaled ). The thread sets the synchronization object as a flag or not based on whether the operation has been completed.

The wait function is used to wait for the state change of the synchronization object. When a thread calls a function and waits for the function, the execution will be paused until the state of the synchronization object changes. The thread will continue to execute the function only after the function is returned. Wait functions are divided into "single object" Wait functions and "multi-object" Wait functions.

Demo
/* UseEvents In the instance first creates an event object, then creates a thread. After the thread is created, after a period of time, the data is copied to the memory, and then set the slot. The created thread EventFunction calls the WaitForSingleObject function to wait for the event to be set. After the event is set, it reads the memory and resets the event to make it unset ). */# include <windows. h> # include <stdio. h>/* global variable */HANDLE hEvent; // used to synchronize BYTE lpSharedBuffer [16] = {0 }; // shared memory/* function declaration */void UseEvents (void); dword winapi EventFunction (LPVOID lpParam); int main () {UseEvents (); system ("pause "); return 0;} void UseEvents (void) {hEvent = CreateEvent (NULL, // Default Security Attribute TRUE, // manually reset FALSE, // The initial value is NULL that is not set // Unnamed); if (hEvent = NULL) // determines whether the creation is successful {printf ("CreateEvent failed (% d) \ n", GetLastError (); return ;} HANDLE hThread; for (int a = 0; a <10; a ++) // create a thread {hThread = CreateThread (NULL, 0, EventFunction, NULL, 0, NULL ); if (hThread = NULL) {printf ("CreateThread failed (% d) \ n", GetLastError (); return;} Sleep (100 ); // you can perform other processing} CopyMemory (lpSharedBuffer, "Event", lstrlen ("Event"); // copy data to the shared memory SetEvent (hEvent );// Set the Event so that the ThreadFunction thread can start to copy data} // thread function, read the shared memory dword winapi EventFunction (LPVOID lpParam) {// wait, until the Event is set to DWORD dwWaitResult = WaitForSingleObject (hEvent, // Event handle INFINITE); // INFINITE wait if (dwWaitResult! = WAIT_OBJECT_0) {printf ("Wait error: % d \ n", GetLastError (); return 0;} printf ("% s \ n", lpSharedBuffer ); // read shared memory if (! ResetEvent (hEvent) // reset event {printf ("SetEvent failed (% d) \ n", GetLastError (); return 0;} return 1 ;}

 

Thread Synchronization Process

The synchronization object works with the wait function to implement thread synchronization. For example, if thread A requires thread B to prepare data for A certain operation, it needs thread synchronization when it is busy. Thread A waits for thread B to run until the required data is ready. The process of using the synchronization object and the wait function is basically as follows:

  • Define A synchronization object in A process that requires thread synchronization. The synchronization object must be global to ensure that the synchronization objects can be accessed by both threads A and B.
  • At the beginning, threads A and B are executed independently of each other.
  • Before preparing the data required by thread A, thread B sets the synchronization object to "unlabeled". After thread B prepares the data required by thread A, it changes the state of the synchronization object, set to "marked ".
  • Thread A runs until the data prepared by thread B is required. If the synchronization object is not "marked", wait until the synchronization object state changes to "marked. After the synchronization object is set to "marked" by B (indicating that thread B has completed data preparation), wait until the function returns, and thread A continues to execute.
  • And so on.

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.