Python threading

这里选自python核心编程第二版的例子
threading模块的多线程实现
两种方式.

第一种提供参数用threading.Thread去构造

import threading
from time import sleep, ctime

loops = [4, 2]

def loop(nloop, nsec):
    print 'start loop', nllp, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()

def main():
    threads = []
    nloops = range(len(loops))
    for i in nloops:
        t = threading.Thread(target=loop,
            args=(i, loops[i]))
        threads.append(t)

    for i in nloops: # start threads
        threads[i].start()

    for i in nloops: # wait for all
        threads[i].join() # threads to finish

if __name__ == '__main__':
    main()

该方法再去在Thread对象构造时, 需要传入工作的函数, 以及工作函数的参数.

但是这里可以将传入的target变为一个callable 对象, 直接在构造Thread的时候
构造一个callable对象丢进去. 这样就不用传入 args参数啦.

可是这样仍然不够直观.
所以我们可以通过使用继承threading.Thread的方法来实现
这是第二种方法哟:

import threading
from time import sleep, ctime

loops = (4, 2)

class MyThread(threading.Thread):
    def __init__(self, func, args, name=""):
        super(MyThread, self).__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        apply(self.func, self.args)   #apply 间接的调用函数


def loop(nloop, nsec):
    print 'start loop', nllp, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()

def main():
    threads = []
    nloops = range(len(loops))

    for i in nloops:
        t = MyThread(loop, (i, loops[i]),
            loop.__name__)
        threads.append(t)

for i in nloops: # start threads
        threads[i].start()

    for i in nloops: # wait for all
        threads[i].join() # threads to finish

if __name__ == '__main__':
    main()

而且threading模块中一个神奇的类
Event
说明是:
A factory function that returns a new event object. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.
默认flag是 False
如果要设置为True 就调用set方法,
如果要重置设置为False就地爱用clear方法.
调用wait()方法会阻塞, 直到flag是True.

一个很简单的方法同步线程.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值