linux-bit operating

During atomic_t type integer arithmetic is good. But it did not work well when you need to manipulate a single atom bits. To this end, the kernel provides a set of functions to modify or atomic test a single bit. Because the entire operation occurs in a single step, without interruption (or other processor) can interfere.

 

Atomic operations very fast, because they use a single machine instruction to operate, and low-level platform at any time to do when not disable interrupts. Functions are declared in the system dependent and <asm / bitops.h> in. Are guaranteed to be atomic , even on an SMP computer, and it is useful for consistency across processors.

 

Unfortunately, the data type of these functions are dependent on the system. NR parameters (to be described the operation which bits) is often defined as the int, unsigned long it is in several systems. To modify the address pointer is often an unsigned long, However, a few systems use void * instead.

 

Various bit operation are:

 

void set_bit(nr, void *addr);

 

Set of nr bit data item pointed to by addr void clear_bit (nr, void * addr).;

Clear the unsigned long data bit addr at its opposite semantics set_bit void change_bit (nr, void * addr)..;

Flip This bit test_bit (nr, void * addr);

This function need not be only a bit operation atoms; it simply returns the current value of this bit.

 

int test_and_set_bit(nr, void *addr); int test_and_clear_bit(nr, void *addr); int test_and_change_bit(nr, void *addr);

 

Atoms operate as listed above, except that they also return to the previous value of this bit.

 

 

When the flag functions used to access and modify such a shared, except that they do not do anything call; they atomic operation occurrence thereof using one control bit operations to manage access to a shared variable lock variable, on the other hand , is somewhat complex and there should be an example. most modern code is not used in this way bit manipulation, but still exists as the following code in the kernel.

 

Section of code requires access to a shared data item is a lock request attempting atoms, or use test_and_set_bit test_and_clear_bit typically implemented show here; it is assumed that nr is the lock-bit in the address addr of the lock is free when it is assumed that the bit is. 0, busy non-zero.

 

/* try to set lock */

while (test_and_set_bit(nr, addr) != 0) wait_for_a_while();

 

/* do your work */

 

/* release lock, and check... */

if (test_and_clear_bit(nr, addr) == 0) something_went_wrong(); /* already released: error */

 

 

If you read through the kernel source, you will be sent a phenomenon code for this example, however, it is best to use spinlocks in new code;. Spinlocks well debugged, they deal with issues like interrupts and kernel preemption, and others read your when the code does not have to try to understand what you are doing.

Guess you like

Origin www.cnblogs.com/fanweisheng/p/11141760.html