一、主线程与小弟进程
import _thread # 多线程
import win32api
def show(i):
# 0 代表系统,你真帅代表内容,来自JOKER代表标题,0代表窗口类型0,1,2,3
mystr = win32api.MessageBox(0,"你真帅","来自Joker的问候",0)
for i in range(5): # 这是小弟线程
# 前面是执行函数,后面是一个元组,可以不写前提是函数没有形参
_thread.start_new_thread(show,(i,))
while True: # 在这里加入死循环是为了脚本主线程不死,小弟线程才能运行
pass
二、多线程速度
import _thread
import time
def go():
for i in range(5):
print(i,"-------")
time.sleep(1)
for i in range(5): # 同时执行5次
_thread.start_new_thread(go,())
for j in range(6): # 让主线程卡顿6秒
time.sleep(1)
print("over")
"""
0 -------
0 -------
0 -------
0 -------
0 -------
1 -------
1 -------
1 -------
1 -------
1 -------
2 -------
2 -------
2 -------
2 -------
2 -------
3 -------
3 -------
3 -------
3 -------
3 -------
4 -------
4 -------
4 -------
4 -------
4 -------
over
"""
前两个案例都不重要
----------------------------------------------华丽的分割线----------------------------------------------------
注:
1、进程中有许多线程
2、线程是资源共享的,谁先抢到谁先运行
3、while True: …pass关掉,则什么都不会出来
4、线程依赖于进程,而进程之间是相互独立的
5、如果主进程死掉则线程也会死掉
三、 线程冲突
import _thread
num = 0
def add():
for _ in range(1000000):
global num
num += 1
print(num)
'''
for j in range(5):
add()
'''
for i in range(5):
_thread.start_new_thread(add,())
while True: # 防止主线程不死
pass
"""
1328487
1477011
1299550
1575149
1636970
"""
5个线程同时抢夺num的资源,导致最后结果错误
import _thread
num = 0
for _ in range(1000000):
num += 1
print(num)
"""
1000000
"""
import _thread
NUM = 0
def A():
global NUM
for i in range(1000000):
NUM += 1
print(NUM)
for i in range(5):
_thread.start_new_thread(A,())
while 1:
pass
"""
1347409
1418017
1468702
1666337
1965287
"""
包_thread不灵活,最好不用
**结果错误:**因为"NUM += 1"加的可能并不是本线程的(抢占资源)
线程比进程消耗少,可以多建几个,但也不能太多
四、基于类实现多线程
import threading
import win32api
class Mythread(threading.Thread): # 继承threading.Thread类
def run(self): # 重写threading.Thread类中的run函数
win32api.MessageBox(0,"hello",'joker',0)
for i in range(5): # 同时创建5个线程
t = Mythread() # 初始化
t.start() # 开启
while True:
pass
import threading
import win32api
class Mythread(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__":
for i in range(5):
t = Mythread()
t.start()
while 1:
pass
"""
1000
1000
1000
1000
1000
"""
**过程:**继承、初始化、重写run(原来在类里)、if、创建五个线程、启动线程、卡死主进程
**每个线程都正确:**重写self.num
import threading
import win32api
NUM = 0
class Mythread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
#self.NUM = 0
def run(self):
global NUM
for _ in range(1000