Entry 3835

redqueue

   

Submitted by anonymous on May 17, 2010 at 4:31 p.m.
Language: Python. Code size: 1.2 KB.

import time
from threading import Thread, Lock
from queue import Queue
from random import random

class REDQueue:
    def __init__(self):
        self.q = Queue()
        self.capacity = 10
        self.length = 0
    def put(self, item):
        if self.length/self.capacity+random() < 1:
            self.q.put(item)
            self.length += 1
            self.draw("+")
            return True
        self.draw(" x")
        return False
    def get(self):
        if self.length <= 0:
            return None
        self.length -= 1
        self.draw("-")
        return self.q.get()
    def draw(self, suffix):
        print("["+( "".ljust(self.length, "-")+
                    "".ljust(self.capacity-self.length, " "))
                    +"] "+suffix)

inc = 0
q = REDQueue()

lock = Lock()

class Putter(Thread):
    def run(self):
        global inc
        while True:
            with lock:
                q.put(inc)
            inc += 1
            time.sleep(0.2)

class Getter(Thread):
    def run(self):
        global inc
        while True:
            with lock:
                q.get()
            time.sleep(0.5)


putter = Putter()
putter.start()


getter = Getter()
getter.start()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).