game_main.py
# coding=utf8
import threading
from logic.consum_thread import ConsumThread
from logic.produce_thread import ProduceThread
if __name__ == "__main__":
lock = threading.Lock()
consumer = ConsumThread(lock)
producer = ProduceThread(lock)
consumer.start()
producer.start()
c_name.py
import time
class CName():
def __init__(self, name):
self.mName = name
self.mStart = time.strftime("%H.%M.%S", time.localtime())
def print(self):
end = time.strftime("%H.%M.%S", time.localtime())
print("CName {} {} {}".format(self.mName, self.mStart, end))
g_global.py
class CGlobal():
def __init__(self):
self.mQueue = []
gGlobal = CGlobal()
produce_thread.py
import threading
import time
from logic.g_global import gGlobal
from logic.c_name import CName
class ProduceThread(threading.Thread):
def __init__(self, lock):
threading.Thread.__init__(self)
self.mLock = lock
def run(self):
count = 0
while(True):
self.mLock.acquire()
gGlobal.mQueue.append(CName("append {} ".format(count)))
count = count + 1
time.sleep(5)
self.mLock.release()
time.sleep(4)
consum_thread.py
# coding=utf8
import time
import threading
from logic.g_global import gGlobal
class ConsumThread(threading.Thread):
def __init__(self, lock):
threading.Thread.__init__(self)
self.mLock = lock
def run(self):
while(True):
self.mLock.acquire()
if len(gGlobal.mQueue) > 0:
cn = gGlobal.mQueue.pop(0)
cn.print()
self.mLock.release()
time.sleep(0.01)
运行效果:
CName append 0 10.10.39 10.10.44
CName append 1 10.10.48 10.10.53
CName append 2 10.10.57 10.11.02
CName append 3 10.11.06 10.11.11
CName append 4 10.11.15 10.11.20
CName append 5 10.11.24 10.11.29