1.setdeamon 当主程序执行完时,子程序自动被销毁 ,内存自动被收回
例一:
import threading, time def run(n):
print('run %s'%n)
time.sleep(1)
print('task %s'%n) t_objs = [] for i in range(10):
m = threading.Thread(target=run, args=(i,))
m.setDaemon(True) #把m子进程设置为守护线程
m.start()
t_objs.append(m) #for t in t_objs:
# t.join() 结果并不会输出 time.sleep(1) 后面的东西,因为直接就跳过了, 例二: 线程之间的相互调用
import threading, time def run(n):
print('task run%s'%n)
time.sleep(1.8)
print('run %s'%n) def main():
for i in range(5):
m = threading.Thread(target=run,args=(i,))
m.start()
m.join(1) #等待第一个m执行一秒钟,一秒钟以后继续循环 my_thread = threading.Thread(target=main,args=()) my_thread.setDaemon(True) #设置为守护程序
my_thread.start() my_thread.join(timeout=2) 2.lock 线程锁 lock 可以保证每次调用时,内部数据只被一个线程操作,保证了不会被重复赋值 例一
import threading def add_number():
lock.acquire()
global number
number += 1
lock.release() number = 0
lock = threading.Lock()
m_objs = []
for i in range(10):
m = threading.Thread(target=add_number, args=())
m.start()
m_objs.append(m) for m in m_objs:
m.join() print(number) 3.threading.BoundedSemaphore 也是一种锁 输出多个线程的结果 例一
import threading, time def run(n):
semaphore.acquire()
print('task run %s'%n)
time.sleep(1)
semaphore.release() if __name__ == '__main__':
semaphore = threading.BoundedSemaphore(5)
for i in range(22):
m = threading.Thread(target=run, args=(i,))
m.start() 4.递归锁 一个大锁里存在着一把小锁 例一:
import threading, time def run_1():
rock.acquire()
print('run_1')
rock.release() def run_2():
rock.acquire()
print('run_2')
rock.release() def run():
rock.acquire()
run_1()
time.sleep(1)
run_2()
rock.release() if __name__ == '__main__': rock = threading.RLock() m = threading.Thread(target=run,args=())
m.start()