ikd29123
ikd29123

Reputation: 21

How to use spinlock in linux?

I am a computer science student, I have one assignment asking me to use spinlock to lock a thread and unlock it once its critical section is completed. The difficulty is I googled many times, but I did not find any useful information. For example, I tried to include header like #include <linux/spinlock.h>, but when I use gcc to compile this c program, it says cannot find such header. So, what header I should include and what functions I need to call in order to use spinlock?

Upvotes: 2

Views: 4948

Answers (2)

brianc
brianc

Reputation: 151

This is an old thread but...

If you are using gcc then you can use these atomic operations to act as simple mutexes/spinlocks, of course assuming you have more than one cpu. Keep in mind your critical section needs to be short or else threads waiting for the lock will chew up cpu while spinning. I've put in a long sleep just to show that it is working.

int lock = 0;   /* lock shared between threads */

printf("waiting for lock...\n");
while ( __sync_lock_test_and_set(&lock, 1));

printf("acquired lock \n");
sleep(2);

__sync_lock_release(&lock);
printf("released lock \n");

Upvotes: 0

linux/spinlock.h is a part of the Linux kernel headers. It isn't a header for Linux program development.

Spinlocks are only suitable when the competing threads are running on different cores. Outside of kernels and certain specialized applications that control exactly which threads are running on which core, what you need is a proper mutex, not a spinlock. Look up the pthread part of the standard Library, specifically the pthread_mutex_xxx functions declared in pthread.h.

If the assignment specifically asks for a spinlock then the goal may be for you to implement a spinlock as a learning exercise. How to do that depends on what primitives you have: the primitives to implement a spinlock depend on the CPU and how to access them depends on the programming language (and for C on the compiler).

Upvotes: 6

Related Questions