美文网首页
python基础知识(五)--多线程编程

python基础知识(五)--多线程编程

作者: Godric_wsw | 来源:发表于2018-09-01 16:48 被阅读13次

1. target指定目标函数来初始化线程

#target指定目标函数来初始化线程
def func(name):
    print('hello %s' % name)
    time.sleep(3)

t_1=threading.Thread(target=func,args=('w',))
t_2=threading.Thread(target=func,args=('s',))
t_1.start()
t_2.start()

2.重写Thread类来初始化线程

#重写Thread类来初始化线程
class mythread(threading.Thread):
    def __init__(self, name):
        super(mythread, self).__init__()
        self.name = name

    def run(self):
        semaphore.acquire()
        print('hello %s' % self.name)
        global num
        lock.acquire()  # 修改数据前加锁
        # 在没释放lock之前,这里不能再用lock.acquire(), 否则会产生死锁
        # 如果有这种应用场景,需要多次使用acquire(), 可以使用Rlock
        #如果要使这个锁生效,还要确保这个锁,是所有线程都可以访问的变量(如全局变量)
        num -= 1#
        lock.release()  # 修改后释放
        print(num)
        time.sleep(3)
        semaphore.release()

semaphore = threading.BoundedSemaphore(1)  # 信号量
lock = threading.Lock()  # 生成全局锁,
#Rlock = threading.RLock()
t1 = mythread('wang')

t2 = mythread('shu')
t2.setDaemon(True)

t1.start()
t2.start()

相关文章

网友评论

      本文标题:python基础知识(五)--多线程编程

      本文链接:https://www.haomeiwen.com/subject/yzsuwftx.html