python 64式: 第13式、线程

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import threading

'''
关键:
1 并发和并行
并发:交替处理多个任务的能力; 关键在并发交替
并行:同时处理多个任务的能力; 关键在并行同时
2 多进程与多线程
多进程可以充分使用多个cpu
多线程不能充分使用多个cpu,原因是全局解释器锁保证同一时刻只能有一个线程可以执行代码。
本质: 每个线程执行时,都需要先获取全局解释器锁
解决方法: 使用多进程完成多任务的处理
3 GIL锁与互斥锁
GIL锁:同一时刻只有一个线程使用cpu
互斥锁:多线程对共享数据的有序修改
4 threading.Thread(target=None, args=(), kwargs={})
使用线程的方式:
方式1: 将要执行的方法放入线程中 
the = threading.Thread(target=myrun, args=(), kwargs{})
the.start()
the.join() # 等待线程完成才退出
方式2: 继承线程类,重写run方法
class MyThread(threading.Thread):
  def run(self):
    pass
5 线程锁
mutex = threding.Lock()
if mutex.acquire():
    pass
    mutex.release()


参考:
https://blog.csdn.net/liangkaiping0525/article/details/79490323
https://blog.csdn.net/weixin_41594007/article/details/79485847

'''

G_MUTEX = threading.Lock()
G_NUM = 0


def myrun(sleepTime):
    time.sleep(sleepTime)
    global G_NUM
    if G_MUTEX.acquire():
        G_NUM += 1
        G_MUTEX.release()

def useMutex():
    threadList = []
    for i in range(3):
        the = threading.Thread(target=myrun, args=(0.1,))
        the.start()
        threadList.append(the)
    # 等待所有线程完成
    for the in threadList:
        the.join()
    assert G_NUM == 3

def process():
    useMutex()

if __name__ == "__main__":
    process()

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/83859137