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()