1

I am using this code in order to visualize how a spinlock would prevent context switching:

pthread_spinlock_t lock;
void pp()
{
        pthread_spin_lock(&lock);
        char d = 'D';
        while(1) write(1, &d, 1);
}
void ppp()
{
        char a = 'C';
        while(1) write(1, &a, 1);
}
int main()
{
        pthread_t thread;
        pthread_t tthread;
        pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE);
        pthread_create(&thread, NULL, pp, NULL);
        pthread_create(&tthread, NULL, ppp, NULL);
        pthread_join(thread, NULL); 
        pthread_join(tthread,NULL);
}

The problem is that I was expecting it to never switch to the second thread, since I never release the lock done in pp(), and to output DDDDDDDDDDDD... because from my understanding, it should prevent context switching. But the output I get is of the form : DCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDC...

How can we explain this? Is my understanding of spinlocks incorrect?

1 Answer 1

2

You need to try to acquire the lock in all threads which are supposed to be mutually exclusive:

void ppp()
{
        pthread_spin_lock(&lock);
        char a = 'C';
        while(1) write(1, &a, 1);
}

Context-switching isn’t prevented by the lock’s existence, you prevent threads from making progress simultaneously by having them try to acquire the same lock. Threads which can’t acquire the lock spin until they can.

4
  • Ok, I understand better how spinlock works. In fact, the difference with other types of synchronization is that we are not descheduling the thread and it has to verify the state of the lock each time, unlike something like semaphore where we make it just sleep. Is this correct?
    – Aramya
    Commented Mar 22, 2022 at 16:56
  • 1
    I’m not sure what you mean by “verify the state of the lock each time”; with any lock, you need to ensure every thread you wish to protect actually acquires the lock. The difference with semaphores is internal to the lock acquisition function: spinlocks spin, semaphores sleep. Commented Mar 22, 2022 at 17:01
  • I meant that when semaphores make a process sleep, it won't even run while the lock is hold, whereas a spin will make it run for nothing until it's released
    – Aramya
    Commented Mar 22, 2022 at 17:05
  • Ah, yes, that’s correct. Commented Mar 22, 2022 at 17:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .