N = 10
class ProCon
data:
mutex:1
empty:N
full:0
front:0
rear:0
buf: []
init:->
i = 0
while i<N
newDom = $('<div class="bufBox"><div class="bufCover">'+i+'</div>'+i+'</div>')
$('#buf').append(newDom)
@data.buf.push 'e'
i++
$('#produce').click =>
@producer()
$('#consume').click =>
@consumer()
p:(num)->
return --num
v:(num)->
return ++num
produceItem:->
$('<p class="desPro">生产了产品</p>').insertBefore $("#des p:first")
return 'm'
consumeItem:->
$('<p class="desCon">消费了产品</p>').insertBefore $("#des p:first")
enterItem:(item) ->
@data.front = (@data.front+1)%N
@data.buf[@data.front] = item;
str = "存入产品#{@data.buf[@data.front]}到缓冲区#{@data.front}"
$("<p class='desPro'>#{str}</p>").insertBefore $("#des p:first")
$($('.bufCover')[@data.front]).animate
"height":"50px"
removeItem:->
@data.rear = (@data.rear + 1) % N;
@data.buf[@data.rear] = 'e';
str = "取出产品#{@data.buf[@data.rear]}从缓冲区#{@data.rear}"
$("<p class='desCon'>#{str}</p>").insertBefore $("#des p:first")
$($('.bufCover')[@data.rear]).animate
"height":"0px"
producer:->
if @data.full==N
$("<p class='desSpe'>缓冲区已全满</p>").insertBefore $("#des p:first")
return
item = @produceItem()
@data.empty = @p(@data.empty)
@data.mutex = @p(@data.mutex)
@enterItem(item)
@data.mutex = @v(@data.mutex)
@data.full = @v(@data.full)
consumer:->
if @data.empty==N
$("<p class='desSpe'>缓冲区已空</p>").insertBefore $("#des p:first")
return
@data.full = @p(@data.full)
@data.mutex = @p(@data.mutex)
@removeItem()
@data.mutex = @v(@data.mutex)
@data.empty = @v(@data.empty)
@consumeItem()
procon = new ProCon
procon.init();