PythonDay07---from DFZY

多线程

1.多线程速度

import _thread
import time
def go():
    for i in range(5):
        print(i,"-------")
        time.sleep(1)

for i in range(5):  
    _thread.start_new_thread(go,())

for j in range(6): 
    time.sleep(1)

print("over")

2.线程冲突

import _thread

num = 0
def A():
    global num
    for _ in range(1000000):
        num += 1
    print(num)

for i in range(5):
    _thread.start_new_thread(A,())

while 1:  
    pass

3.基于类的多线程
threading.Thread类
重写threading.Thread类中的run函数

import threading

class Hwh(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.NUM = 0
    def run(self):
        for _ in range(1000):
            self.NUM += 1
        print(self.NUM)

if __name__ == "__main__":
    ts = []
    for i in range(5):
        t = Hwh()
        t.start()
        ts.append(t)

    for t in ts:
        t.join()

    print('over')

4.start() , join()

import threading
import win32api


class Mythread(threading.Thread):   # 继承threading.Thread类
    def run(self):  # 定义函数
        win32api.MessageBox(0,"hello",'hwh',0)


for i in range(5):
    t = Mythread()  # 初始化
    t.start()  # 开启
    # 等待一个线程执行完毕,再执行下一个线程,一方面可以阻止脚本主线程死掉,另一方面也可以防止线程冲突的一种办法
    t.join()
# t.join() 如果将其放在外部的不确定因素是,系统给for 循环和下面的代码锁定了一片内存,当循环执行完成之后,
# 内存就开锁了,但是里面的东西还依然存在,所以才结束一个窗体,game over就出来了,
# 就和删除文件后,内存中可能还有文件一样的道理

print("game over")

5.打印100个验证码

import random
import threading


class Hwh(threading.Thread):
    def __init__(self,lock):
        threading.Thread.__init__(self)
        self.lock = lock
        self.list_ = []
    
    def run(self):
        for i in range(50):
            res = random.randint(1000,9999)
            print(res)
            self.list_.append(res)

        with self.lock:
            self.write(self.list_)

    def write(self,num):
        b = [str(x)+'\n' for x in num]
        b = ''.join(b)
        with open('res.txt',mode='a') as file:
            file.write(b)

if __name__ == "__main__":
    ts = []
    lock = threading.Lock()
    for i in range(2):
        t = Hwh(lock)
        t.start()
        ts.append(t)
    for t in ts:
        t.join()
    print('over')

6.线程通信

import threading
import time


def A(e):
    e.wait()
    print('Hello')

def B(e):
    time.sleep(3)
    e.set()

if __name__ == "__main__":
    e = threading.Event()
    t1 = threading.Thread(target=A,args=(e,))
    t2 = threading.Thread(target=B,args=(e,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

带装饰器线程通信

import threading
import time
import random

def deco2(times):
    def deco(func):
        def warp(*args,**kwargs):
            e = args[0]
            time.sleep(times)
            e.set()
            return func(*args,**kwargs)
        return warp
    return deco

@deco2(5)
def A(e):
    e.wait()
    print('hello')

if __name__ == "__main__":
    e = threading.Event()
    t = threading.Thread(target=A,args=(e,))
    t.start()
    t.join()

你可能感兴趣的:(DFZY)