小探py线程

先偿试一下比较低级一些的Thread
下篇再偿试封装更好的Threading

Coding:

__anthor__='jave.lin'

import thread
import Queue
import time
import random

def test(locker, threadName, r, q):
    print("at %f, %s getting the lock\m" % (time.time(), threadName))
    locker.acquire() #blocking the thread if the locker.locked() in this thread or anthor thread
    sleepSeconds = r.randint(1, 5)
    print("at %f, %s got the lock, and sleep %d seconds\n" % (time.time(), threadName, sleepSeconds))
    time.sleep(sleepSeconds)
    print("at %f, %s release the lock\n" % (time.time(), threadName))
    locker.release()
    print("thread%d, exit\n" % q.get())
    q.task_done() #tell the queue one task done, until all the task done, Queue.join will unblocking

def main():
    r = random.Random()
    l = thread.allocate_lock()
    q = Queue.Queue()
    for i in xrange(5):
        q.put(i)
        thread.start_new_thread(test, (l, "thread%d" % i, r, q))
    print("waitting for all the thread action complete!\n")
    q.join()
    print("all thread action complete, "),
    print("exitting the testThread.py")

if __name__=='__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值