多线程模块:thread

thread 是一个比较低级别的模块,官方推荐我们使用 threading 替代 thread, thread 常见用法如下:

thread.start_new_thread(function, args):开启一个新的线程,接收两个参数,分别为函数和该函数的参数,相当于开启一个新的线程来执行这个函数,注意函数的参数必须是元组类型的,例子如下,开启两个线程同时输出声音和画面

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time
import thread

def fun(name, n):
    for i in range(n):
        print name, i
        time.sleep(1)

thread.start_new_thread(fun, ('声音', 3))
thread.start_new_thread(fun, ('画面', 3))

time.sleep(3)    # 这里要停止几秒,否则没等线程执行完进程就退出了
[root@localhost ~]$ python 1.py 
画面 0
声音 0
画面 1
声音 1
画面 2
声音 2

thread.allocate_lock():用于创建一个锁对象,我们可以同时开启多个线程,但是在任意时刻只能有一个线程在解释器运行,因此需要由全局解锁器(GIL)控制运行哪个线程,锁对象的常用方法如下:

    

    

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10353953.html