python threading 模块来实现多线程

本文介绍了一个使用Python实现的多线程日志打印程序。通过定义两个不同的线程类PrintThread和PrintThread2,每个线程负责在一定时间内向标准输出打印指定数量的日志信息。为了确保日志打印的有序性,程序中使用了锁机制来控制多个线程对标准输出的访问。

以多线程的方式向标准输出打印日志 

 

#!/usr/bin/python

import time
import threading

class PrintThread(threading.Thread):
    def __init__(self,threadid,count,mutex):
        threading.Thread.__init__(self)
        self.threadid=threadid
        self.count=count
        self.mutex=mutex
    def run(self):
        with self.mutex:
            for item in range(self.count):
                time.sleep(0.05)
                print 'threadid is {0} this is the count {1}'.format(self.threadid,item)

class PrintThread2(threading.Thread):
    def __init__(self,threadid,count,mutex):
        threading.Thread.__init__(self)
        self.threadid=threadid
        self.count=count
        self.mutex=mutex
    def run(self):
        for item in range(self.count):
            with self.mutex:
                time.sleep(0.1)
                print 'thread id is {0} this is the count {1}'.format(self.threadid,item)

if __name__=="__main__":
    threads=[]
    stdoutLock=threading.Lock()
    for item in range(5):
        pt=PrintThread2(item,100,stdoutLock)
        threads.append(pt)
        pt.start()
    for item in threads:
        item.join()
    print 'this end ...'
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值