码迷,mamicode.com
首页 > 编程语言 > 详细

线程--守护线程、线程锁、信号量、事件、条件、定时器、队列、池(三)

时间:2019-05-18 18:40:59      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:main   jin   时间片轮转   lex   进程   lease   自己   join()   自带   

守护线程

技术图片

 

import time
from threading import Thread
def func1():
while True:
print(‘*‘*10)
time.sleep(1)
def func2():
print(‘in func2‘)
time.sleep(5)

t = Thread(target=func1,)
t.daemon = True
t.start()
t2 = Thread(target=func2,)
t2.start()
t2.join() #加join后会等待func2结束后在打印
print(‘主线程‘)

# 守护进程随着主进程代码的执行结束而结束
# 守护线程会在主线程结束之后等待其他子线程的结束才结束

# 主进程在执行完自己的代码之后不会立即结束 而是等待子进程结束之后 回收子进程的资源
# import time
# from multiprocessing import Process
# def func():
# time.sleep(5)
#
# if __name__ == ‘__main__‘:
# Process(target=func).start()

 

 

线程锁

技术图片

为什么Cpython自带GIL锁还出现死锁,因为是对线程GIL锁,避免不了时间片轮转带来数据不安全

 技术图片

import time
from threading import Lock,Thread
# Lock 互斥锁(只有一个钥匙)
# def func(lock):
# global n
# lock.acquire()
# temp = n
# time.sleep(0.2)
# n = temp - 1
# lock.release()
#
# n = 10
# t_lst = []
# lock = Lock()
# for i in range(10):
# t = Thread(target=func,args=(lock,))
# t.start()
# t_lst.append(t)

# for t in t_lst: t.join()
# print(n)



# 科学家吃面

# noodle_lock = Lock()
# fork_lock = Lock()
# def eat1(name):
# noodle_lock.acquire()
# print(‘%s拿到面条啦‘%name)
# fork_lock.acquire()
# print(‘%s拿到叉子了‘%name)
# print(‘%s吃面‘%name)
# fork_lock.release()
# noodle_lock.release()
#
# def eat2(name):
# fork_lock.acquire()
# print(‘%s拿到叉子了‘%name)
# time.sleep(1)
# noodle_lock.acquire()
# print(‘%s拿到面条啦‘%name)
# print(‘%s吃面‘%name)
# noodle_lock.release()
# fork_lock.release()
#
# Thread(target=eat1,args=(‘alex‘,)).start()
# Thread(target=eat2,args=(‘Egon‘,)).start()
# Thread(target=eat1,args=(‘bossjin‘,)).start()
# Thread(target=eat2,args=(‘nezha‘,)).start()
执行上面代码后出现死锁阻塞
技术图片







解决死锁问题

技术图片
from threading import RLock # 递归锁(一串钥匙,多少根据accquire多少次)
fork_lock = noodle_lock = RLock() # 一个钥匙串上的两把钥匙
def eat1(name):
noodle_lock.acquire() # 一把钥匙
print(‘%s拿到面条啦‘%name)
fork_lock.acquire()
print(‘%s拿到叉子了‘%name)
print(‘%s吃面‘%name)
fork_lock.release()
noodle_lock.release()

def eat2(name):
fork_lock.acquire()
print(‘%s拿到叉子了‘%name)
time.sleep(1)
noodle_lock.acquire()
print(‘%s拿到面条啦‘%name)
print(‘%s吃面‘%name)
noodle_lock.release()
fork_lock.release()

Thread(target=eat1,args=(‘alex‘,)).start()
Thread(target=eat2,args=(‘Egon‘,)).start()
Thread(target=eat1,args=(‘bossjin‘,)).start()
Thread(target=eat2,args=(‘nezha‘,)).start()

线程--守护线程、线程锁、信号量、事件、条件、定时器、队列、池(三)

标签:main   jin   时间片轮转   lex   进程   lease   自己   join()   自带   

原文地址:https://www.cnblogs.com/mys6/p/10886510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!