如何避免spinlock

如果Semaphore这样实现,就可能导致spinlock:

   

        acquire(){
            while(value <= 0)
                ; //no-op
            value--;
        }    
        release(){
            value++;
        }            
    

当进程等待时,cpu会空转,也就是说进程会spin(自旋),导致CPU浪费。

   

所以应该改空转为阻塞,把cpu让给操作系统的scheduler. 恐龙书上介绍的实现为:

   

        acquire(){
            value--;
            if(value < 0){
                add this process to list;
                block();
            }
        }

        release(){
            value++;
            if(value <= 0){
                remove a process P from list
                wakeup(P);
            }
        }    
    

   

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.