Semaphore and Mutex

In my project of sina spider as well as the course of Operating System, I come up with the use of Semaphore and Mutex, I make a note here for my study and my work.

Definition

In computer science, a semaphore is a variable or abstract data type provides a simple but useful abstraction controlling access by multiple processes to a common resource in a parallel programming environment.

Semaphores are a useful tool in the prevention of race conditions; however, their use is by no means a guarantee that a program is free from these problems. Semaphores which allow an arbitrary resource count are called counting semaphores, while semaphores which are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores (same functionality that mutexes have).

 

P & V:

operation P:

//apply for a resource

Semaphore--;

//if allocation fails, the process sleeps

if(Semaphore < 0)

        sleep();

operation V:

//release a resource

Semaphore++;

//if resource is avaliable, wake up a process

if(Semaphore > 0)

          wakeupaprocess() 

 

Semaphore vs. mutex

A mutex is essentially the same thing as a binary semaphore, and sometimes uses the same basic implementation. However, the term "mutex" is used to describe a construct which prevents two processes from accessing a shared resource concurrently. The term "binary semaphore" is used to describe a construct which limits access to a single resource.

In many cases a mutex has a concept of an "owner": the process which locked the mutex is the only process allowed to unlock it. In contrast, semaphores generally do not have this restriction, something the producer-consumer example above depends upon.

 

Example 1: A Mutex Example

Description:

      There is a classroom , if a student enters it, variable 'conunt' increases by 1, and if a student exits it, variable 'conunt' decreases by 1.

Solution:

      Initialize mutex = 1

      Enter:

      P(mutex)

  count++

  V(mutex)

  Exit:

      P(mutex)

  count--

  V(mutex)

 

Example 2: Use in my Crawler 

Description:

In one of my Crawler for Sina microblog, I use parallel programming and there is a UID stack that need to be locked while one thread is visiting it, and when the top element of UID stack is poped out, the lock can be released. So I used the Semaphore to deal with it.

Solution:

      Initialize mutex = 1

      With the control of UID Stack:

      P(mutex)

  UIDStack.top()

  UIDStack.pop()

  V(mutex)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值