python 多线程

Python线程模块 threading

获取当前线程 threading.current_thread()

创建线程 threading.Thread(group=none, target=none, name=none, args=(), kwargs={})

group:线程组,还没有实现,引用时必须是none

target:要执行的方法名,注意方法名后面不要跟着括号

name:创建的线程的名字

args/kwargs:要传入方法的参数

 

开始线程 实例.start()

# _*_ coding:utf-8_*_
import time
import threading


def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
print('Thread %s >>> %s' % (threading.current_thread().name, n))
n +=1
time.sleep(1)
print('Thread %s ended' % threading.current_thread().name)

print('thread %s is running' % threading.current_thread().name)
t = threading.Thread(target=loop, name='loopthread') # 创建线程,target是要执行的方法 name是线程的名称
t.start() # 开始线程
t.join()
print('thread %s ended' % threading.current_thread().name)

在使用全局变量时,必须给线程加锁 lock,threading.Lock(),不然多线程对全局变量的修改会导致结果出错
使用线程自己的局部变量时可以不用加锁
# _*_ coding:utf-8_*_
import time
import threading


def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
print('Thread %s >>> %s' % (threading.current_thread().name, n))
n +=1
time.sleep(1)
print('Thread %s ended' % threading.current_thread().name)

print('thread %s is running' % threading.current_thread().name)
t = threading.Thread(target=loop, name='loopthread') # 创建线程,传入线程执行的函数和参数
t.start() # 开始线程
t.join()
print('thread %s ended' % threading.current_thread().name)

ThreadLocal全局变量,解决线程之间参数的传递问题
local_school = threading.local()  # 定义个全局变量


def process_student():
std = local_school.student
print('Hello, %s is in %s' % (std, threading.current_thread().name))


def process_thread(std):
local_school.student = std
process_student()

std1 = threading.Thread(target=process_thread, name='Thread-A')
std2 = threading.Thread(target=process_thread, name='Thread-B')
std1.start()
std2.start()
std1.join()
std2.join()

posted on 2018-03-26 17:18  永恒自由森林  阅读(221)  评论(0编辑  收藏  举报

导航