python多线程

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值