Search

Using Spinlock in linux : Example

In the post we see the various functions available for spinlock in Linux. Let us look at an example and see how it can be used in Linux.

In the following example we create two threads, thread1 and thread2. We initialize a spinlock "my_lock" and both the threads try to acquire the lock .

Thread1 is made to get to the lock first. After acquiring the lock thread1 waits for one minute before releasing the lock.

During this time thread2 attempts to acquire the lock too. We have used the function spin_trylock, so if the thread2 is unable to hold the spinlock it will return immediately with a return value of non zero.

Thus we will define a spinlock using



Starting with the spinlock in unlocked state.

We will create the two threads thread_fn1 and thread_fn2 using the function kthread_create.

The first thread function thread_fn1 will hold the lock and loop for approximately on minute the code for which is



The second thread function thread_fn2 will try to hold try to hold the lock using spin_trylock.A sleep of 100ms is added at the beginning to make sure that the first thread gets to the lock first.Thus the code for the second thread function will be



If the thread_fn2 is able to get the lock we will see the message "Lock acquired" in the kernel log. If the thread_fn2 is unable to get the lock we will see the message "Unable to hold lock" in the kernel log.

The complete code will be

spinlock_example.c



Save the file as spinlock_example.c

Makefile required for compilation.



Compile and load the file



To check if second thread was able to get the lock run the command dmesg



Thus we can see that the spin_trylock faile to acquire the lock and returned the error message. Instead of spin_trylock if we use spin_lock, the second thread will wait on the lock as long as the thread does not become available.

Note: Do not try changing the code from spin_trylock to spin_lock if you have a uniprocessor system. It might freeze your system and force you to do hard reboot.


Follow by Email