zoukankan      html  css  js  c++  java
  • 线程、锁、递归锁、信号量

    线程的直接调用:

    import threading   #直接调用
    def run2(n):      #函数名可以随便起
        n = '吞噬者'
        print('rhread %s is start'% n)
    t = threading.Thread(target=run2,args='n')   #生成一个线程实例
    t.start()

    线程的继承式调用:

    import threading      #继承式调用
    class Mythreading(threading.Thread):
        def __init__(self,n):
            super(Mythreading,self).__init__()    #重写构造方法,继承基类
            self.n = n
        def run(self):              #函数名必须是 run
            print('线程 %s 已启动' % self.n)
    t = Mythreading('吞噬者')
    t.run()

    锁:

    import threading,time
    number = 0
    def run2(n):  #定义每个线程要运行的函数
        lock.acquire()    #在修改数据之前加锁,加锁之后,程序立刻变成串行
        global number
        number += 1
        time.sleep(1)
        lock.release()
        #修改结束释放锁   以此来避免重复修改数据(这种情况只会在2.x中出现,3.xzhong1不会重复修改,可以理解为3.x自己将这一块儿优化了,但是还是得加锁)
        print('线程启动:',n,threading.current_thread(),threading.active_count())
        #threading.current_thread()显示线程类型,是主线程还是子线程
        #threading.active_count()   显示当前活跃的线程数
        print('线程执行结束')
    lock = threading.Lock()             #申请一把锁
    t_objs = []                         #用来存线程实例
    std = time.time()
    for i in range(100):
        t = threading.Thread(target=run2,args=('t - %s' % i,))
        # t.setDaemon(True)               #将当前线程变成守护线程
        t.start()
        t_objs.append(t)                #为了不阻塞后面线程的启动,不在这儿join(等待),先放在一个列表里
    for a in t_objs:                    #循环线程实例列表,等待所有线程执行完毕
        a.join()   #等待
    print(time.time() - std)
    print('num:',number)
    print('全部结束了',threading.current_thread(),threading.active_count())

    信号量:

    #Author:SS
    import threading,time   #每次最多5个线程同时运行
    def run(n):
        semaphore.acquire()       #加信号量
        time.sleep(1)
        print('run the thread: %s
    ' % n)
        semaphore.release()       #释放
    semaphore = threading.BoundedSemaphore(5) #申请信号量 最多允许5个线程同时运行
    for i in range(20):
        t = threading.Thread(target=run,args=(i,))
        t.start()
    while threading.active_count() != 1:
        pass
    else:
        print('线程全部结束!')
  • 相关阅读:
    迷宫 填充法新思路(填充干扰路径)
    类模板使用说明
    thinkphp5项目--企业单车网站(二)
    thinkphp5项目--企业单车网站(一)
    thinkphp5项目--个人博客(八)
    PHP 二维数组去掉重复值并保持原结构
    PHP join() 函数
    PHP array_merge() 函数
    thinkphp5项目--个人博客(七)
    PHP str_replace() 和str_ireplace()函数
  • 原文地址:https://www.cnblogs.com/ss-py/p/8630896.html
Copyright © 2011-2022 走看看