python,多线程应用示例

Posted Iceberg_710815

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python,多线程应用示例相关的知识,希望对你有一定的参考价值。

应用python的threading模块开启多线程执行程序,会缩短程序运行时间,下面代码演示了多线程应用

#不开启多线程演示
import time,threading
def foo(n):
    print(foo%s%n)
    time.sleep(1)
def bar(n):
    print(bar%s%n)
    time.sleep(2)
begin = time.time()
t1 = threading.Thread(target = foo,args = (1,))
t2 = threading.Thread(target = bar,args = (2,))
#t1.start()
#t2.start()
foo(1)
bar(2)
end = time.time()
process_time = end - begin
print(process time is:%s%(str(process_time)))

上面不开启多线程的情况下执行结果如下:

/usr/bin/python3.6 /home/guoming/python/day27/thread.py
foo1
bar2
process time is:3.003460168838501

Process finished with exit code 0
程序运行花了3秒时间

#改写一下,开启两个线程
import time,threading
def foo(n):
print(‘foo%s‘%n)
time.sleep(1)
def bar(n):
print(‘bar%s‘%n)
time.sleep(2)
begin = time.time()
t1 = threading.Thread(target = foo,args = (1,))
t2 = threading.Thread(target = bar,args = (2,))
t1.start()
t2.start()
#foo(1)
#bar(2)


print(‘......main.........‘)
t1.join()
t2.join()
end = time.time()
process_time = end - begin
print(‘process time is:%s‘%(str(process_time)))

开启线程后执行结果如下:

/usr/bin/python3.6 /home/guoming/python/day27/thread.py
foo1
bar2
......main.........
process time is:2.0026726722717285

Process finished with exit code 0
程序用了2秒

以上是关于python,多线程应用示例的主要内容,如果未能解决你的问题,请参考以下文章

python小白学习记录 多线程爬取ts片段

python下多线程是鸡肋,推荐使用多进程 代码示例

python多线程

[Python3] 043 多线程 简介

python中的多线程和多进程编程

在多线程应用程序中使用屏障的真实示例是啥?