123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- #!/usr/bin/python
- from threading import Thread, Lock
- import time
- def hexstr(b):
- x="["
- for i in range(len(b)):
- if i>0: x+=", "
- x+=hex(b[i])
- return x+"]"
- class Queue:
- def __init__(self, size=1024):
- self.head=0
- self.tail=0
- self.alloc=size
- self.data=[]
- self.mutex=Lock()
- for i in range(self.alloc): self.data.append(None)
-
- def enqueue(self, x):
- self.mutex.acquire()
- self.data[self.tail]=x
- self.tail= (self.tail+1)%self.alloc
- self.mutex.release()
-
-
- def dequeue(self):
- while self.isEmpty(): time.sleep(0.001)
- self.mutex.acquire()
- x=self.data[self.head]
- self.head=(self.head+1)%self.alloc
- self.mutex.release()
- return x
-
- def __length(self):
- if self.head>self.tail:
- return self.alloc-(self.head-self.tail)
- return self.tail-self.head
-
- def length(self):
- self.mutex.acquire()
- x= self.__length()
- self.mutex.release()
- return x
-
- def isEmpty(self):
- return self.length()==0
-
- def peek(self):
- self.mutex.acquire()
- x=self.data[self.head]
- self.mutex.release()
- return x
-
- def contains(self, x):
- n=self.length()
- ok=False
- self.mutex.acquire()
- for i in range(self.head, self.head+n):
- j=i%self.alloc
- if self.data[j] == x:
- ok=True
- break
- self.mutex.release()
- return ok
-
|