首先对python3实现多线程的threading库函数做简单介绍
- run(): 用以表示线程活动的方法
- tart():启动线程活动。
- join([time]): 等待至线程中止。
- isAlive(): 返回线程是否活动的。
- getName(): 返回线程名。
- setName(): 设置线程名
- getpid(): 得到线程的pid编号。
1.多线程程序简单实现
import threading
import time
def play_Game(num):
for i in range(num):
print("play game %d" % i)
#休眠使多线程得到体现
time.sleep(1)
def watch_Tv(num):
for i in range(num):
print(" watch_Tv %d" % i)
time.sleep(1)
def main():
"""创建多线程"""
t_game = threading.Thread(target = play_Game,args = (5,))
t_tv = threading.Thread(target = watch_Tv,args = (6,))
"""启动多线程"""
t_game.start()
t_tv.start()
if __name__ == '__main__':
main()
运行结果如下:
继承方式:
通过继承Thread类,并重写init()和run()方法实现多进程
import time
import threading
class MyThread(threading.Thread):
def __init__(self,counter):
super().__init__()
self.counter = counter
def run(self):
print(f'线程名称:{threading.current_thread().name}')
counter = self.couter
while counter:
time.sleep(3)
counter -= 1
def main():
print(f'主线程开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
start = time.time()
# 初始化3个线程,传递不同的参数
t1 = MyThread(3)
t2 = MyThread(2)
t3 = MyThread(1)
# 开启三个线程
t1.start()
t2.start()
t3.start()
# 等待运行结束并回收资源
t1.join()
t2.join()
t3.join()
end = time.time()
print(f'主线程结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
print("运行时间为:%s" % (end-start))
if __name__ == '__main__':
main()
运行结果如下:
3.线程池
通过ThreadPoolExecutor实现线程池
from concurrent.futures import ThreadPoolExecutor
import os
import time
import random
def task(n):
print('%s is running' %s os.getpid())
time.sleep(random.randint(1,3))
return n*n
def main():
#通过max_workers参数设置线程池的最大线程数
executor = ThreadPoolExecutor(max_workers=3)
futures = []
for i in ranger(10):
#通过submit把task函数和i参数传入
future = executor.submit(task,i)
futures.append(future)
executor.shutdown(True)
print('----->>>>>'
for future in futures:
print(future.result())
if __name__ == '__main__':
main()
执行结果如下:
因为多线程程序容易导致计算结果出错
其原因是因为python的一个语句在解释时会变成多个语句从而使得逻辑错误,其解决方法有event,queue,semaphore.lock等方法。
例如:
import time
import threading
num = 0
def task_thread(n):
global num
#获取锁
lock.acquire()
for i in range(1000000):
num = num + n
num = num - n
#释放锁
lock.release()
def main():
t1 = threading.Thread(target=task_thread,args(6,))
t2 = threading.Thread(target=task_thread,args(10,))
t3 = threading.THread(target=task_thread,args(9,))
start = time.time()
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
end = time.time()
print("执行时间为:%s" % (end-start))
print(num)
if __name__ == '__main__':
main()
执行结果为:
1.lock锁方法
import time
import threading
num = 0
lcok = threading.Lock()
def task_thread(n):
global num
#获取锁
lock.acquire()
for i in range(1000000):
num = num + n
num = num - n
#释放锁
lock.release()
def main():
t1 = threading.Thread(target = task_thread,args=(6,))
t2 = threading.Thread(target = task_thread,args=(10,))
t3 = thread.Thread(target = task_thread,args=(9,))
start = time.time()
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
end = time.time()
print("执行时间为:%s" % (end-start))
print(num)
if __name__ == '__main__':
main()
执行结果为:
通过queue实现对同一类资源的限制访问
解决最大供给和需求的问题
import threading
import time
import queue
#fifo
q = queue.Queue(maxsize = 5)
def Produce():
count = 1
while True:
q.put('产品 %s' % count)
print('存储: %s' % count)
count += 1
time.sleep(1)
def Consume():
while True:
print('消费 %s' % q.get())
time.sleep(5)
def main():
p = threading.Thread(target = Produce)
c = threading.Thread(target = Consume)
p.start()
c.start()
if __name__ == '__main__':
main()
执行结果为: