import time

import queue
import threading


class LogQueue(queue.Queue):

    def __init__(self, lock):
        self._lock = lock
        self.writes = 0

        super(self.__class__, self).__init__()

    def _dump(self):
        print('\n=======')
        with self._lock:
            while not self.empty():
                print('GOT', self.get())
            time.sleep(0.5)
        print('=======\n')

    def put(self, *args, **kwargs):
        super(self.__class__, self).put(*args, **kwargs)

        self.writes += 1
        if self.writes == 5:
            self.writes = 0
            self._dump()

    # def __del__(self):
    #     self._log.close()


def writer(lock, log, condition):
    i = 0
    while True:
        if i == 15:
            return

        if condition(i):
            with lock:
                log.put(i)
                print('PUT', i)
        time.sleep(0.1)
        i += 1


lock = threading.RLock()
log = LogQueue(lock)

threading.Thread(target=writer, args=(lock, log, lambda i: i % 2 == 0)).start()
threading.Thread(target=writer, args=(lock, log, lambda i: i % 2 != 0)).start()
