zoukankan      html  css  js  c++  java
  • python 线程

    一、基础知识

    1、线程和进程的区别与联系

    进程是资源分配的最小单位,线程是cpu调度的最小单位

    一个进程至少有一个线程,cpu直接调用线程

    2、优点

    线程的调度用时小于进程

    线程之间共享进程的数据

    线程有较小的数据栈,数据不共享

    3、GIL(全局解释器锁)

    在Cpython解释器下,同一时间,多个线程只能有一个线程被cpu执行

    锁的是线程

    Cpython解释器导致了这个问题

    二、创建线程

    函数

    import time
    from threading import Thread
    
    
    def test(n):
        time.sleep(0.2)
        print(n+1)
    
    
    t_li = []
    for i in range(10):
        t = Thread(target=test, args=(i, ))     # 异步
        t_li.append(t)
        t.start()
    
    [t.join() for t in t_li]
    print('Hello, World1')

    面向对象

    import time
    from threading import Thread
    
    
    class MyThread(Thread):
        def __init__(self, args):
            super(MyThread, self).__init__()
            self.args = args
    
        def run(self) -> None:
            time.sleep(1)
            print(pow(self.args, 2))
    
    
    t_li = []
    for i in range(5):
        t = MyThread(i)
        t_li.append(i)
        t.start()
    [t.join() for i in t_li]
    print('===============================')

    三、常用方法

    import threading
    import time
    
    
    def su(n, m):
        print(threading.current_thread())
        print(threading.get_ident())
        time.sleep(1)
        print(n + m)
    
    
    t = threading.Thread(target=su, args=(1, 3))
    t.start()
    # t.join()
    print('主线程: %s' % threading.current_thread())       # 获取线程的名称
    print('激活进程数量:%s' % threading.active_count())   # 获取线程的ID
    print('主线程ID: %s' % threading.get_ident())      # 获取当前激活的线程
    print(threading.enumerate())    # 枚举当前的所有线程
  • 相关阅读:
    BRVAH(让RecyclerView变得更高效)(1)
    爬虫开发python工具包介绍 (4)
    爬虫开发python工具包介绍 (3)
    爬虫开发python工具包介绍 (2)
    爬虫开发python工具包介绍 (1)
    小白用shiro(2)
    hdu 1010 走到终点时刚好花掉所有时间 (DFS + 奇偶性剪枝 )
    vijos 1128 N个数选K个数 (DFS )
    poj 1321 棋盘问题(n行中放任意k行)
    DFS基础题
  • 原文地址:https://www.cnblogs.com/wt7018/p/11067130.html
Copyright © 2011-2022 走看看