这篇文章给大家分享的是有关python中线程处理之threading模块的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
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()
感谢各位的阅读!关于“python中线程处理之threading模块的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.xuebuyuan.com/3253735.html