Reprinted please indicate the source and the author contact: http://blog.csdn.net/mimepp
Contact information: Yu Tao <yut616 at Sohu dot com>
Usage and precautions of list head in applications
List head connectors that are frequently used in kernel are also of great application value in general applications. Take a note here.
The list head contains only Prev and next, but no data. This is the biggest difference between it and the linked list in our general usage, and it is much more flexible.
Example code:/usr/src/linux-headers-2.6.28-11-generic/include/Linux/list. h
Struct list_head {<br/> struct list_head * Next, * Prev; <br/> };
In addition, the list_entry method is quite special.
We can write a small program to verify the features of List entry.
# Include <stdio. h> <br/> # include <stdlib. h> <br/> struct test_s {<br/> int A; <br/> int B; <br/>}; <br/> void main () <br/>{< br/> struct test_s hello; <br/> printf ("% P, % d/N", & (struct test_s *) 0) -> B), (struct test_s *) 0)-> B); <br/>}
(GDB) B test. c: 11 <br/> breakpoint 1 at 0x80483d5: file test. c, line 11. <br/> (GDB) r <br/> starting program:/work/. out <br/> breakpoint 1, main () at test. c: 11 <br/> 11 printf ("% P, % d/N", & (struct test_s *) 0)-> B ), (struct test_s *) 0)-> B); <br/> (GDB) P & (struct test_s *) 0)-> B) <br/> $1 = (int *) 0x4 <br/> (GDB) P (struct test_s *) 0) -> B <br/> cannot access memory at address 0x4 <br/>
Here we can see that access to pointer & (struct test_s *) 0)-> B is allowed, and access to the corresponding content is illegal.
Note:
1. Thread Security
In actual use, pay special attention to the use of list_for_each_safe. It should be noted that list_for_each_safe is not safe for multithreading, but it is safe for a single process.
If it is used in multiple threads, you need to add lock to protect list operations.
2. Head Position in list
# Define list_for_each (Pos, head)/<br/> for (Pos = (head)-> next; prefetch (POS-> next), pos! = (Head);/<br/> Pos = pos-> next) <br/>
In this loop, we can see that POS starts from head-> next until it is not end with head. That is to say, there is a head in the list, this is also different from the general linked list. Generally, the operation is from the first operation to the last one, but the list head is not.
This is mainly because the head does not have a corresponding entry, so it is skipped to operate on other POS.