utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/python
  2. from threading import Thread, Lock
  3. import time
  4. def hexstr(b):
  5. x="["
  6. for i in range(len(b)):
  7. if i>0: x+=", "
  8. x+=hex(b[i])
  9. return x+"]"
  10. class Queue:
  11. def __init__(self, size=1024):
  12. self.head=0
  13. self.tail=0
  14. self.alloc=size
  15. self.data=[]
  16. self.mutex=Lock()
  17. for i in range(self.alloc): self.data.append(None)
  18. def enqueue(self, x):
  19. self.mutex.acquire()
  20. self.data[self.tail]=x
  21. self.tail= (self.tail+1)%self.alloc
  22. self.mutex.release()
  23. def dequeue(self):
  24. while self.isEmpty(): time.sleep(0.001)
  25. self.mutex.acquire()
  26. x=self.data[self.head]
  27. self.head=(self.head+1)%self.alloc
  28. self.mutex.release()
  29. return x
  30. def __length(self):
  31. if self.head>self.tail:
  32. return self.alloc-(self.head-self.tail)
  33. return self.tail-self.head
  34. def length(self):
  35. self.mutex.acquire()
  36. x= self.__length()
  37. self.mutex.release()
  38. return x
  39. def isEmpty(self):
  40. return self.length()==0
  41. def peek(self):
  42. self.mutex.acquire()
  43. x=self.data[self.head]
  44. self.mutex.release()
  45. return x
  46. def contains(self, x):
  47. n=self.length()
  48. ok=False
  49. self.mutex.acquire()
  50. for i in range(self.head, self.head+n):
  51. j=i%self.alloc
  52. if self.data[j] == x:
  53. ok=True
  54. break
  55. self.mutex.release()
  56. return ok