In: Computer Science
Answer the following questions based on the C code provided.
typedef int simple_spinlock_t;
int simple_spin_init(simple_spinlock_t* lock) { // The next line
sets the compile time memory fence
__asm__ __volatile__("" ::: "memory");
// here we set the flag to zero. Apparently “unlocked” is zero
Exciting, right?
*lock = 0; return 0;
}
int simple_spin_lock(simple_spinlock_t* lock)
{
int i;
while (1)
{
for (i=0; i < 5000; i++)
if (__sync_bool_compare_and_swap(lock, 0, 1)
return 0;
sched_yield();
}
}
int simple_spin_unlock(simple_spinlock_t *lock)
{
__asm__ __volatile__("" ::: "memory");
*lock = 0; return 0;
}
int c = 0;
simple_spinlock_t lock; // declare the lock variable as a global
void* fnC() {
int i;
for (i = 0; i < 10; i++)
{
simple_spin_lock(&lock); // Lock the critical section
c++; printf(" %d", c);
simple_spin_unlock(&lock); // Unlock the critical section
}
}
int main() {
int rt1, rt2; pthread_t t1, t2; int trial_count = 0;
simple_spin_init(&lock); // Initialize the lock flag
for (trial_count = 0; trial_count < 50; trial_count++)
{
c = 0;
/* Create two threads */
if ((rt1 = pthread_create(&t1, NULL, &fnC, NULL)))
printf("Thread creation failed: %d\n", rt1);
if ((rt2 = pthread_create(&t2, NULL, &fnC, NULL)))
printf("Thread creation failed: %d\n", rt2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("\n");
}
return 0;
}
a.Firstly, spinning is just a loop where CPU keep looping itself to check on a variables value.If that value changes another CPU will modify it.
In a single CPU system another CPU will not be there and the CPU will just spin wait eternally.
So when we compile this all the spinlocks are not compiled into kernel.
b.Spinlock is mutual exclusion that has two values locked and unlocked, operations must be done in an automatic manner so that only one thread can obtain the lock even several are spinning at the given time.Here, if the lock is available the locked bit is set and code continues into critical section.
If the locks has been taken by someone else code goes into loop where it repeatedly checks the lock until its available. This part of of loop is spin.
If a non preemptive unprocessed system ever went into a spin,it would spin forever no other thread would be able to obtain the CPU to release the lock.