Python-----threading多线程

本文介绍了如何在Python中使用threading模块创建线程,包括定义函数、创建线程实例、处理Windows错误以及使用全局变量和互斥锁。重点讲解了如何避免函数作为Thread目标时的参数问题,并演示了共享资源的同步控制。
摘要由CSDN通过智能技术生成

threading介绍

threading是Python的标准库,用于创建线程,其方法是先定义几个函数,传给threading的Thread类,用该类的run()方法启动线程

threading项目(同时输出hello和hello1)

导入threading

先导入threading

import threading

定义函数

定义第一个线程的函数,打印10次hello

def print_hello_thread():
    for i in range(10):
       print('hello')

在定义第二个线程的函数,打印10次hello1

def print_hello1_thread():
    for i in range(10):
        print('hello1')

定义线程

定义完两个函数后,将两个函数定义为线程,分别放到两个变量中

hello_thread = threading.Thread(target=print_hello_thread)
hello1_thread = threading.Thread(target=print_hello1_thread)

注意:线程的target变量函数不能有()因为hello()和hello1这两个函数的返回值为'None',我们要传给这个类的是这两个函数不是'None',而是hello和hello1这两个函数

启动线程

接下来我们要启动线程,调用Thread这个类的run方法启动线程

hello_thread.run()
hello1_thread.run()

windows上的问题

如果在windows上报错解决方法如下:

在创建并运行的地方加上if __name__ == '__main__':

说明​​:__name__为当前运行的模块,如果是'__main__'说明当前的模块为主模块,也就是直接运行的模块。

if __name__ == '__main__':
    hello_thread = threading.Thread(target=hello)
    hello1_thread = threading.Thread(target=hello1)
    hello_thread.run()
    hello1_thread.run()

共享全局变量

直接使用global设置全局变量就可以了,例如:

import threading


#定义一个全局变量
foods = []
lock = threading.Lock()
#线程2
def beef():
    global foods
    for i in range(100):
        foods.append('beef')
       

    

#线程1
def apple():
    global foods
    for i in range(100):
        foods.append('apple')

if __name__ == '__main__':
    add_apple = threading.Thread(target=apple)
    add_beef = threading.Thread(target=beef)
    add_apple.run()
    add_beef.run()
   

互斥锁

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值