C # Programming Summary (iii) thread synchronization

Source: Internet
Author: User
Tags comparison mutex resource semaphore thread

One advantage of using multiple threads in an application is that each thread can execute asynchronously. For Windows applications, time-consuming tasks can be performed in the background, allowing application windows and controls to remain responsive. For server applications, multithreading provides the ability to process each incoming request with a different thread. Otherwise, each new request cannot be processed until the previous request is fully satisfied. However, the asynchronous nature of threads means that access to resources, such as file handles, network connections, and memory, must be coordinated. Otherwise, two or more threads may access the same resources at the same time, and each thread does not know what the other threads are doing.

"If it feels useful, please help the top!" If there is a shortage, welcome to the Brick!

How threads are synchronized

Thread synchronization has: critical section, Mutex, event, Semaphore four Ways

Difference between critical sections (Critical section), mutexes (mutexes), semaphores (semaphore), Events (event)

1, critical area: Through the serialization of multithreading to access public resources or a section of code, fast, suitable for controlling data access. Only one thread is allowed to access the shared resource at any time. If more than one thread attempts to access a public resource, after one thread enters, other threads that attempt to access the public resource are suspended and wait until the thread entering the critical section leaves and the critical section is freed before other threads can preempt it.

2, mutual exclusion: the use of mutually exclusive object mechanism. Only a thread that has a mutex has access to a public resource because there is only one mutex, so that public resources are not accessed by multiple threads at the same time. Mutual exclusion not only realizes the common resources security sharing of the same application, but also realizes the security sharing of public resources of different applications.

3. Semaphore: It allows multiple threads to access the same resource at the same time, but needs to limit the maximum number of threads that access the resource at the same time

4, Events: the way to notify the operation to maintain the synchronization of threads, but also to facilitate the implementation of multiple threads of priority comparison operations

Common thread synchronization methods in C #

We introduce several common C # thread synchronization methods that can be used to find one of the four types that correspond to the above.

1, interlocked
Provides atomic operations for variables that are shared by multiple threads.

According to experience, those resources that need to be protected in multi-threaded situations are usually integer values, and the most common operation of these integer values in multithreading is the increment, decrement, or addition operation. The Interlocked class provides a dedicated mechanism for accomplishing these specific operations. This class provides a increment, decrement, add static method for incrementing, decreasing, or adding an int or a long variable. Methods of this class can prevent errors that may occur when a scheduler switches the context when a thread is updating a variable that can be accessed by another thread, or when two threads execute concurrently on a different processor. Members of this class do not throw exceptions.

The Increment and decrement methods increment or decrement the variable and store the resulting value in a single operation. On most computers, adding a variable operation is not an atomic operation, and you need to perform the following steps:

1 load the value in the instance variable into the register.
2) Increase or decrease the value.
3 Store The value in the instance variable.
If you do not use Increment and decrement, the thread is preempted after the first two steps are executed. Then the other thread executes all three steps. When the first thread restarts execution, it overwrites the value in the instance variable, resulting in the loss of the result of the second thread performing the increment or decrement operation.

The Exchange method automatically swaps the value of the specified variable. The CompareExchange method combines two actions: Compares two values and stores the third value in one of the variables based on the results of the comparison. The comparison and exchange operations are performed as atomic operations.

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.