您当前的位置: 首页 > 

Jave.Lin

暂无认证

  • 1浏览

    0关注

    704博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

小探py线程

Jave.Lin 发布时间:2016-08-31 16:17:05 ,浏览量:1

先偿试一下比较低级一些的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()
关注
打赏
1664331872
查看更多评论
立即登录/注册

微信扫码登录

0.0416s