线程,守护线程,死锁——》递归锁,信号量

Posted 河北凝讯科技订阅号

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程,守护线程,死锁——》递归锁,信号量相关的知识,希望对你有一定的参考价值。

一线程:

        1,什么是线程:

                进程其实不是一个执行单位,进程是一个资源单位

                每个进程内自带一个线程,新城才是cpu上的执行单位

                如果把操作系统比喻为一座工厂

                        在工厂内每造出一个车间====》启动一个进程

                        每个车间内至少有一条流水线====》每个进程内至少有一个线程

                线程==》单只代码的执行过程

                进程==》资源的申请与销毁的过程

            2,进程vs线程

                    1,多个进程内存空间彼此隔离

                    2,同一个进程下的多个线程共享该进程内的数据

                    3,制造线程的速度要远远快于制造进程

                    举例子:

                    #1、线程的开启速度快
                    # from threading import Thread
                    # from multiprocessing import Process
                    # import time
                    # def task(name):
                    #     print('%s is running' %name)
                    #     time.sleep(3)
                    #     print('%s is done' %name)
                    #
                    # if __name__ == '__main__':
                    #     t=Thread(target=task,args=('子线程',))
                    #     # t=Process(target=task,args=('子进程',))
                    #     t.start()

                    #     print('主')

                    #2、同一进程下的多个线程共享该进程内的数据
                    # from threading import Thread
                    # import time
                    #
                    # x=100
                    # def task():
                    #     global x
                    #     x=0
                    #
                    # if __name__ == '__main__':
                    #     t=Thread(target=task,)
                    #     t.start()
                    #     # time.sleep(3)
                    #     t.join()

                    #     print('主',x)#子线程可以修改进程中的数据

                    # 查看pid
                    from threading import Thread
                    import time,os
                    def task():
                        print(os.getpid())
                    if __name__ == '__main__':
                        t=Thread(target=task,)
                        t.start()

                        print('主',os.getpid())

二:线程对象的其他方法和属性

            # 主进程等子进程是因为主进程要给子进程收尸
            # 进程必须等待其内部所有线程都运行完毕才结束
            # from threading import Thread
            # import time
            #
            # def task(name):
            #     print('%s is running' %name)
            #     time.sleep(3)
            #     print('%s is done' %name)
            # if __name__ == '__main__':
            #     t=Thread(target=task,args=('子线程',))
            #     t.start()

            #     print('主')

            

            from threading import Thread,current_thread,active_count,enumerate
            import time

            def task():
                print('%s is running' % current_thread().name)#获取当前线程的名字
                time.sleep(3)
                print('%s is done' % current_thread().name)
            if __name__ == '__main__':
                t = Thread(target=task,name='xxx')
                t.start()
                # t.join()
                # print(t.is_alive())#判断子线程是否存活
                # print(t.getName())#查看子线程的名字
                # print(t.name)
                # print('主',active_count())#查看活跃的线程个数
                # print(enumerate())#将产生的进程对象存成列表的形式
                # t.join()
                current_thread().setName('主线程')
                print('主',current_thread().name)

三:守护线程:

        # 守护线程会在本进程内所有非守护的线程都死掉了才跟着死
        # 即:
        # 守护线程其实守护的是整个进程的运行周期(进程内所有的非守护线程都运行完毕)
        # from threading import Thread,current_thread
        # import time
        # def task():
        #     print('%s is running' % current_thread().name)
        #     time.sleep(3)
        #     print('%s is done' % current_thread().name)
        # if __name__ == '__main__':
        #     t = Thread(target=task,name='守护线程')
        #     t.daemon=True
        #     t.start()

        #     print('主')

        迷惑的例子:

        from threading import Thread
        import time
        def foo():
            print(123)
            time.sleep(1)
            print("end123")
        def bar():
            print(456)
            time.sleep(3)
            print("end456")
        t1=Thread(target=foo)
        t2=Thread(target=bar)
        t1.daemon=True
        t1.start()
        t2.start()
        print("main-------")
        '''    #打印结果子线程并不会马上死掉,会等到非守护线程bar运行完毕才死掉
        123
        456
        main-------
        end456

        '''

四:互斥锁

        from threading import Thread,Lock
        import time
        mutex=Lock()#互斥锁
        x=100
        def task():
            global x
            # mutex.acquire()#如果不加互斥锁会对数据的修改产生错乱
            temp=x
            time.sleep(0.1)
            x=temp-1
            # mutex.release()
        if __name__ == '__main__':
            t_l=[]
            start=time.time()
            for i in range(100):
                t=Thread(target=task)
                t_l.append(t)
                t.start()
            for t in t_l:
                t.join()
            stop=time.time()
            print(x,stop-start)

五:死锁与递归锁

            from threading import Thread,Lock,active_count,RLock
            import time
            # mutexA=Lock()#普通的互斥锁
            # mutexB=Lock()
            obj=RLock() #递归锁的特点:可以连续的acquire
            mutexA=obj
            mutexB=obj
            class Mythread(Thread):
                def run(self):
                    self.f1()

                    self.f2()


                def f1(self):
                    mutexA.acquire()
                    print('%s 拿到A锁' %self.name)
                    mutexB.acquire()
                    print('%s 拿到B锁' %self.name)
                    mutexB.release()

                    mutexA.release()


                def f2(self):
                    mutexB.acquire()
                    print('%s 拿到B锁' %self.name)
                    time.sleep(1)
                    mutexA.acquire()
                    print('%s 拿到A锁' %self.name)
                    mutexA.release()
                    mutexB.release()
            if __name__ == '__main__':
                for i in range(10):
                    t=Mythread()
                    t.start()
                # print(active_count())

六:信号量

            # 信号量是控制同一时刻并发执行的任务数
            from threading import Thread,Semaphore,current_thread
            import time,random
            sm=Semaphore(5)#同时可以并发执行五个任务数
            def task():
                with sm:
                    print('%s 正在上厕所' %current_thread().name)
                    time.sleep(random.randint(1,4))
            if __name__ == '__main__':
                for i in range(20):
                    t=Thread(target=task)
                    t.start()

*   版权声明:转载文章和图片均来自公开网络,版权归作者本人所有,推送文章除非无法确认,我们都会注明作者和来源。如果出处有误或侵犯到原作者权益,请与我们联系删除或授权事宜

以上是关于线程,守护线程,死锁——》递归锁,信号量的主要内容,如果未能解决你的问题,请参考以下文章

并发编程: 生产消费模型死锁与Rlock线程守护线程信号量锁

python 线程(创建2种方式,守护进程,锁,死锁,递归锁,GIL锁,其他方式)

线程的创建 验证线程之间共享数据 守护线程 线程进程效率对比 锁 死锁 递归锁

死锁现象与解决方案,开启线程的2种方式,守护线程,线程VS进程,线程互斥锁,信号量

36 线程 队列 守护线程 互斥锁 死锁 可重入锁 信号量

并发编程目录