static DEFINE_SPINLOCK(synctime_lock);

This is a statement that defines a spinlock (spin lock) in the Linux kernel. DEFINE_SPINLOCKIs a macro in the kernel used to define and initialize a spinlock. Its parameter is the name of the spinlock you want to define. Here, synctime_lockit is the name of the spinlock you defined. Spinlock is a simple locking mechanism. When a thread attempts to acquire a spinlock that is already occupied, it will wait (i.e. spin, constantly checking the lock status in a loop instead of going to sleep) until the spinlock becomes available. This locking mechanism is useful in processor-addressed data structures and time-sensitive code, such as in hardware interrupt service routines.

The keyword here staticmeans that this spinlock is only visible in the file in which it is defined. DEFINE_SPINLOCKThe lock is already initialized, so you can use it immediately without requiring additional initialization in your code. However, it should be noted that the holding time of spinlock should be kept as short as possible, and operations that may cause task switching or sleep should not be performed during the holding period.

Spinlock is a low-level lock. Its characteristic is that when the thread cannot obtain the lock immediately, it will keep waiting there, or "spin", until the lock is released. The advantage of this mechanism is that it reduces the overhead caused by thread blocking and waking up, and is very effective for situations where the lock acquisition time is short. However, if the lock is held for a long time, the spin lock may occupy a large amount of CPU resources, causing system performance to degrade. At the same time, when using spinlock, if a thread holding the lock enters sleep or a task switch occurs, other threads waiting for the lock can only spin and wait, because they do not know the thread holding the lock. When can you wake up and release the lock? This may cause unnecessary waste of CPU time, and if the priority of the preempted thread is higher, it may cause priority inversion.

Therefore, the spin lock should be kept as short as possible, and operations that may cause task switching or sleep should not be performed during the holding period. This is to minimize the time that threads waiting for the spin lock waste CPU resources. .

Guess you like

Origin blog.csdn.net/qq_41483419/article/details/132906489