现在的位置: 首页 > 编程语言 > 正文

python 中的线程处理——threading模块

2018年08月29日 编程语言 ⁄ 共 1618字 ⁄ 字号 评论关闭

转自:http://www.oschina.net/code/snippet_16840_1815

python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。thread是比较底层的模 块,threading是对thread做了一些包装的,可以更加方便的被使用。这里需要提一下的是python对线程的支持还不够完善,不能利用多 CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧。

    threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。一般来说,使用线程有两种模式,一种是创建线程要执行的 函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。我们来看看这两种做法吧。

#-*- encoding: gb2312 -*-
02
import string, threading, time
03
 
04
def thread_main(a):
05
    global count, mutex
06
    # 获得线程名
07
    threadname = threading.currentThread().getName()
08
     
09
    for x in xrange(0, int(a)):
10
        # 取得锁
11
        mutex.acquire()
12
        count = count + 1
13
        # 释放锁
14
        mutex.release()
15
        print threadname, x, count
16
        time.sleep(1)
17
     
18
def main(num):
19
    global count, mutex
20
    threads = []
21
     
22
    count = 1
23
    # 创建一个锁
24
    mutex = threading.Lock()
25
    # 先创建线程对象
26
    for x in xrange(0, num):
27
        threads.append(threading.Thread(target=thread_main, args=(10,)))
28
    # 启动所有线程
29
    for t in threads:
30
        t.start()
31
    # 主线程中等待所有子线程退出
32
    for t in threads:
33
        t.join() 
34
     
35
     
36
if __name__ == '__main__':
37
    num = 4
38
    # 创建4个线程
39
    main(4)
[代码] [Python]代码
view sourceprint?
01
#-*- encoding: gb2312 -*-
02
import threading
03
import time
04
 
05
class Test(threading.Thread):
06
    def __init__(self, num):
07
        threading.Thread.__init__(self)
08
        self._run_num = num
09
     
10
    def run(self):
11
        global count, mutex
12
        threadname = threading.currentThread().getName()
13
     
14
        for x in xrange(0, int(self._run_num)):
15
            mutex.acquire()
16
            count = count + 1
17
            mutex.release()
18
            print threadname, x, count
19
            time.sleep(1)
20
 
21
if __name__ == '__main__':
22
    global count, mutex
23
    threads = []
24
    num = 4
25
    count = 1
26
    # 创建锁
27
    mutex = threading.Lock()
28
    # 创建线程对象
29
    for x in xrange(0, num):
30
        threads.append(Test(10))
31
    # 启动线程
32
    for t in threads:
33
        t.start()
34
    # 等待子线程结束
35
    for t in threads:
36
        t.join() 

抱歉!评论已关闭.