Python——多线程(上)

本文介绍了Python中的多线程概念,包括主线程与子线程的关系、线程冲突问题及解决方案。通过实例展示了线程的顺序风格和乱序风格,并讲解了如何使用锁(lock)来避免线程冲突。此外,还探讨了死锁和活锁的概念,以及线程通信的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、主线程与小弟进程

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值