Data access mutex of multithreaded programming

Source: Internet
Author: User

In an environment where multithreading exists, all data is shared except for temporary data in the stack. If we need to run correctly between threads, it is important to ensure that the execution and calculation of public data is correct. Simply put, it is guaranteed that the data must be mutually exclusive at the time of execution. Otherwise, if two or more threads manipulate the data at the same time, the consequences are unthinkable.

Ensure that data access is mutually exclusive across multiple threads, with the following four types of methods:

(1) off interrupt

(2) Mathematical Mutex method

(3) Mutually exclusive methods provided by the operating system

(4) CPU atomic operation

These four methods are described in more detail below:

(1) off interrupt

Since interrupt switching between multiple threads can cause different steps to access the same data, turning off thread break switching will definitely avoid this problem. Also, there is a real shutdown interrupt instruction in the Intel X86 series CPU. Refer to the following code:

#include <stdio.h>  int main ()  {      __asm{          cli          sti      }      return 1;  }

Where the CLI is off interrupt, STI is on interrupt. This code has no problem, can be made up, of course, can also generate execution files. However, an exception alarm will appear when executing: Unhandled exception in test.exe:0xc0000096:privileged instruction. The alarm has been made clear that this is a privileged command. This command can only be used by the system or the kernel itself.

However, you can imagine. Because usually we write programs are application-level programs, if each program is to use the code, it is not a mess. For example, you accidentally install a low-quality software, maybe when you turn off the interruption, so that your network is broken, your input is not responding, your music is nothing, such an environment you suffer from it? Application layer software is very diverse, the level of software is also uneven, so the system can not trust any proprietary software, it believes that it is only its own. In short, as an application development, this approach is certainly undesirable.

(2) Data method

With a mathematical algorithm, you can ensure that only one of the different threads may access one data. For example, there are two threads that operate the same variable and can use the following algorithm:

unsigned int flag[2] = {0};unsigned int turn = 0;void process (unsigned int index) {    Flag[index] = 1;    turn =  1-index;    while (Flag[1-index] && (turn = = (1-index)));    Do_something ();    Flag[index] = 0;}

In fact, learned the operating system of friends know that the above algorithm is actually the Peterson algorithm, unfortunately it can only be used for two threads of data mutex. Of course, this algorithm can also be generalized to the mutual exclusion between more threads, that is the bakery algorithm. However, there are two disadvantages of the mathematical algorithm:

A) occupy a lot of space, two threads will be flag accounted for two units of space, then n a thread will be n flag space;

b) The complexity of code writing, and the complexity of consideration.

(3) Mutually exclusive methods provided by the operating system

The mutex algorithm provided by the system is actually the most mutually exclusive tool we develop in our usual development. For Windows, there are critical areas, mutexes, semaphores, and so on for mutually exclusive tools. Such algorithms have a feature, that is, based on the system to improve the mutually exclusive resources, then the system is how to complete these functions? It's not that hard, actually.

One of the simplest ways to implement a system lock:

void Lock (HANDLE hlock) {    __asm {CLI};    while (1) {        if (/* Lock available */) {/            * Set flag indicating that the current lock is occupied */            __asm {STI};            return;        }        __asm{sti};        Schedule ();        __ASM{CLI};}    } void UnLock (HANDLE hlock) {    __asm {CLI};    /* Set flag, current lock available */    __asm{sti};}

It can be seen from the code that a simple system lock can be achieved by using the interrupt shutdown and the Open command of the CPU. However, this example does not take into account the readiness of the thread stack and other issues, the actual situation will be more complex.

(4) CPU atomic operation

In multi-threading often involves a frequently used and very simple calculation operation, this time using mutexes, semaphores and other mutually exclusive operation is not cost-effective. As a result, CPU vendors design some common operations as atomic instructions, which are also called atomic locks in Windows systems. Common atomic operations include the following:

Interlockedaddinterlockedexchangeinterlockedcompareexchangeinterlockedincrementinterlockeddecrementinterlockedandinterloc Kedor

Data access mutex of multithreaded programming

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.