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())    # 枚举当前的所有线程
  • 相关阅读:
    Mysql数据库--自学笔记--2
    Mysql数据库--自学笔记--1
    Python--作业3--模拟ATM程序的流程
    Python--数据存储:json模块的使用讲解
    如果我能成功,你也能
    有意注意到底有多重要
    没有人喜欢听废话——讲重点
    回顾你的一天是多么的重要
    思考的力量
    多问为什么,肯定不会错
  • 原文地址:https://www.cnblogs.com/wt7018/p/11067130.html
Copyright © 2011-2022 走看看