Sample Header Ad - 728x90

How does a spinlock prevents context switching?

1 vote
1 answer
1055 views
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?
Asked by user514788
Mar 22, 2022, 03:58 PM
Last activity: Mar 22, 2022, 04:12 PM