2

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?

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
ikd29123
  • 21
  • 1
  • 3
  • Please post your complete `gcc` command with all arguments. Is your `-I` (include path) argument correct? – Dai Nov 26 '16 at 22:34
  • Kernel headers seem an odd choice here. There's `pthread_spin_init`, `pthread_spin_lock`, `pthread_spin_unlock` and `pthread_spin_destroy` in `` you could use, but really this sounds as though you're supposed to implement your own spin lock. – Wintermute Nov 26 '16 at 22:45

2 Answers2

6

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).

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
0

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");
brianc
  • 131
  • 1
  • 6