Python学习笔记23:多线程
import time
import threading
loop = [4, 2]
class ThreadFunc:
def __init__(self, name):
self.name = name
def loop(self, nloop, nsec):
#nloop:loop函数的名称
#nsec:系统休眠时间
print('Start loop', nloop, 'at', time.ctime())
sleep(nsec)
print('Done loop', nloop, 'at', time.ctime())
def main():
print("starting at:", time.ctime())
#ThreadFunc('loop').loop 跟一下两个式子相等
#t = ThreadFunc('loop')
#t.loop
#以下t1, t2的定义方式相等
t = ThreadFunc('loop')
t1 = threading.Thread(target = t.loop, args = ('Loop1', 4))
t2 = threading.Thread(target = ThreadFunc('loop').loop, args = ('Loop2', 2))
t1.start()
t2.start()
t1.join()
t2.join()
print('all done at:', time.ctime())
if __name__ == '__main__':
main()
threading的使用:
-直接利用threading.Thread生成Thread实例
1.t = threading.Thread(target = xxx, args = (xxx,))
2.t.start(): 启动多线程
3.t.join():等待多线程执行完成
守护线程:
-如果在程序中将子线程设置为守护线程,则子线程会在主线程结束的时候自动退出
-一般认为,守护线程不重要或者不允许离开主线程独立运行
线程常用属性:
-threading.currentThread: 返回当前线程变量
-threading.enumerate: 返回一个包含正在运行的线程的list,正在运行的线程指的是线程启动后,结束前的
-threading。activeCount:返回正在运行的线程数量,效果跟len(threading.enumerate)相同
-thr.setName: 给线程设置名字
-thr.getName:得到线程的名字
共享变量:当多个线程同时访问一个变量的时候,会产生共享变量的问题
import threading
sum = 0
loopSum = 100000
def myAdd():
global sum, loopSum
for i in range(1, loopSum):
sum += 1
def myMinu():
global sum, loopSum
for i in range(1, loopSum):
sum -= 1
if __name__ == '__main__':
print('start.....{0}'.format(sum))
t1 = threading.Thread(target = myAdd, args = ())
t2 = threading.Thread(target = myMinu, args = ())
t1.start()
t2.start()
t1.join()
t2.join()
print('done.....{0}'.format(sum))
锁:哪个资源需要多个线程,就锁谁
import threading
sum = 0
loopSum = 100000
lock = threading.Lock()
def myAdd():
global sum, loopSum
for i in range(1, loopSum):
lock.acquire() #上锁
sum += 1
lock.release() #释放锁
def myMinu():
global sum, loopsum
for i in range(1, loopSum):
lock.acquire()
sum -= 1
lock.release()
if __name__ == '__main__':
print('starting.....{0}'.format(sum))
t1 = threading.Thread(target = myAdd, args = ())
t2 = threading.Thread(target = myMinu, args = ())
t1.start()
t2.start()
t1.join()
t2.join()
print('done.....{0}'.format(sum))
锁:哪个资源需要多个线程,就锁谁
可重入锁:可以被一个线程多次申请