python3的多线程实现

首先对python3实现多线程的threading库函数做简单介绍

  1. run(): 用以表示线程活动的方法
  2. tart():启动线程活动。
  3. join([time]): 等待至线程中止。
  4. isAlive(): 返回线程是否活动的。
  5. getName(): 返回线程名。
  6. setName(): 设置线程名
  7. 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()

运行结果如下:
thread1

继承方式:
通过继承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()

运行结果如下:
thread2
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()

执行结果如下:
thread3
因为多线程程序容易导致计算结果出错
其原因是因为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()

执行结果为:
thread5

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()

执行结果为:
thread4
通过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()

执行结果为:
thread6

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值