Atomic manipulation of multithreaded programming

Source: Internet
Author: User
Tags volatile

In a multithreaded environment, access to shared variables can be implemented using the lock free technology based on compare and swap, the benefit of which is high efficiency.

An extract of atomic operation

1.1 Android

Source: system/core/libcutils/atomic.c (for X86):

1 #elifDefined (__i386__) | | Defined (__x86_64__)2 3 voidAndroid_atomic_write (int32_t value,volatileint32_t*addr) {4 int32_t OldValue;5      Do {6OldValue = *addr;7} while(Android_atomic_cmpxchg (oldValue, value, addr));8 }9 Tenint32_t Android_atomic_inc (volatileint32_t*addr) { One int32_t OldValue; A      Do { -OldValue = *addr; -} while(Android_atomic_cmpxchg (OldValue, oldvalue+1, addr)); the     returnOldValue; - } -  -int32_t Android_atomic_dec (volatileint32_t*addr) { + int32_t OldValue; -      Do { +OldValue = *addr; A} while(Android_atomic_cmpxchg (OldValue, oldvalue-1, addr)); at     returnOldValue; - } -  -int32_t Android_atomic_add (int32_t value,volatileint32_t*addr) { - int32_t OldValue; -      Do { inOldValue = *addr; -} while(Android_atomic_cmpxchg (OldValue, oldvalue+value, addr)); to     returnOldValue; + } -  the intAndroid_atomic_cmpxchg (int32_t oldvalue, int32_t newvalue,volatileint32_t*addr) { *     intXchg; $AsmvolatilePanax Notoginseng     ( -         "lock; Cmpxchg%%ecx, (%%edx);" the         "Setne%%al;" +         "Andl $,%%eax" A:"=a"(XCHG) the:"a"(OldValue),"C"(NewValue),"D"(addr) +     ); -     returnXchg; $}
View Code

ANDROID_ATOMIC_CMPXCHG is implemented using the GNU C embedded assembler, using the X86 provided by the Atomic support for CAS directive. The oldvalue is placed in the EAX register, NewValue is placed in ecx, and addr (pointer) is placed in edx. The CMPXCHG instruction first compares the memory that addr points to oldvalue (EAX), and if they are equal, puts NewValue (ECX) in the memory pointed to by addr and sets the Z flag 1. The result of the operation of the Setne and ANDL instructions is simple: If the z flag is set, then the EAX is 0, otherwise 1. The final eax of the program execution is placed in the XCHG variable.

It can be seen that the self-increment and decrement operations are implemented based on ANDROID_ATOMIC_CMPXCHG, which successfully returns 1, and the failure returns 0, for example:

5 ; int B = Android_atomic_cmpxchg (A, A +1, &a);p rintf ("%d,%d\n"  , A, b);         // output when successful: 6,1 // output when failed: 5,0

1.2 IOS

Header files: #include <libkern/OSAtomic.h>

Operation

Function Name

Description

Add

OSAtomicAdd32
Osatomicadd32barrier
OSAtomicAdd64
Osatomicadd64barrier

Adds together and stores the result in one of the specified variables.

Increment

OSAtomicIncrement32
Osatomicincrement32barrier
OSAtomicIncrement64
Osatomicincrement64barrier

Increments the specified integer value by 1.

Decrement

OSAtomicDecrement32
Osatomicdecrement32barrier
OSAtomicDecrement64
Osatomicdecrement64barrier

Decrements the specified integer value by 1.

Logical OR

OSAtomicOr32
Osatomicor32barrier

Performs a logical OR between the specified 32-bit value and a 32-bit mask.

Logical and

OSAtomicAnd32
Osatomicand32barrier

Performs a logical and between the specified 32-bit value and a 32-bit mask.

Logical XOR

OSAtomicXor32
Osatomicxor32barrier

Performs a logical XOR between the specified 32-bit value and a 32-bit mask.

Compare and swap

OSAtomicCompareAndSwap32
Osatomiccompareandswap32barrier
OSATOMICCOMPAREANDSWAP64
Osatomiccompareandswap64barrier
Osatomiccompareandswapptr
Osatomiccompareandswapptrbarrier
Osatomiccompareandswapint
Osatomiccompareandswapintbarrier
Osatomiccompareandswaplong
Osatomiccompareandswaplongbarrier

Compares a variable against the Specified old value. If The values is equal, this function assigns the specified new value to the variable; Otherwise, it does nothing. The comparison and assignment is done as one atomic operation and the function returns a Boolean value indicating whether The swap actually occurred.

Test and set

Osatomictestandset
Osatomictestandsetbarrier

Tests a bit I n the specified variable, sets that bit to 1, and returns the value of the old bit as a Boolean value. Bits is tested according to the formula (0x80 >> (N & 7)) of a Byte ((char*) address + (n >> 3)) where n is t The He bit number and address are a pointer to the variable. This formula effectively breaks up the variable to 8-bit sized chunks and orders the bits in each chunk in reverse. For example, to test the Lowest-order bit (bit 0) of a 32-bit integer, you would actually specify 7 for the bit number; Similarly, to test the highest order bit (bit), you would specify for the bit number.

Test and clear

Osatomictestandclear
Osatomictestandclearbarrier

Tests a bit in the specified variable, sets this bit to 0, and returns the value of the old bit as a Boolean value. Bits is tested according to the formula (0x80 >> (N & 7)) of a Byte ((char*) address + (n >> 3)) where n is t The He bit number and address are a pointer to the variable. This formula effectively breaks up the variable to 8-bit sized chunks and orders the bits in each chunk in reverse. For example, to test the Lowest-order bit (bit 0) of a 32-bit integer, you would actually specify 7 for the bit number; Similarly, to test the highest order bit (bit), you would specify for the bit number.

These operations, may be concerned about the function of the return value, the return value in the programming of the description of the document is good, more convenient.  The official website document explains this: thearithmetic operations return the new value, after the operation have been performed. The Boolean operations come in the styles, one of the which returns the new value, and one of the which (the "Orig" versions) Retu  RNs the old.  The Compare-and-swap operations return True if the comparison was equal, ie if the swap occured.  The bit test and set/clear operations return the original value of the bit. The dequeue operation returns the most recently enqueued element, or NULL if the list is in empty.

1.3 Windows

The operations on the Windows platform are generally similar, and the functions of the InterlockedIncrement, InterlockedDecrement series are known, and it is important to note that the two functions return the new value after the operation, not the original value before the operation.

Header Windows.h
Library Coredll.lib
Windows Embedded CE Windows CE. NET 4.0 and later
Windows Mobile Windows Mobile Version 5.0 and later

Atomic manipulation 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.