自学内容网 自学内容网

python 多线程

文章目录

    • 1.学习目的
    • 2.线程与进程
    • 3.多线程
    • 4.多线程实现
  • @File: 241008多线程.py
  • @Author: chen_song
  • @Time: 2024/10/8 下午2:58
  • 实现多线程三种方式 进程?线程?
    • 5.reference

在这里插入图片描述

1.学习目的

最近有朋友私信说线程这部分有点晕,于是写下这篇文章希望对他有用

2.线程与进程

线程是计算机可以资源分配与调度最小单元,可以有多个线程,但是至少一个主线程main
在这里插入图片描述

3.多线程

在这里插入图片描述

4.多线程实现

@File: 241008多线程.py

@Author: chen_song

@Time: 2024/10/8 下午2:58

实现多线程三种方式 进程?线程?

try:
 import threading
except ImportError:
 import dummy_threading as threading

import _thread
import sys
import time


def job():
 print("这是一个查看路径的任务。。。")
 print(sys.argv)
 print("current thread is:", threading.current_thread())
 print("current thread num is ", threading.get_ident())
 print("活跃线程个数:", threading.active_count())


def job2():
  print("current thread is:", threading.current_thread())

def job3():
  print("current thread is:", threading.current_thread())

class myThread(threading.Thread):
  def __init__(self, target):
   threading.Thread.__init__(self)
   self.target = target
  def run(self):
   print("current thread is ", self.target)


if __name__ == '__main__':

 condition = threading.Condition()
 condition.acquire()
 threading.Thread(target=job2()).start()
 condition.release()
 threading.Thread(target=job()).start()
 #   开启一个自定义线程
 time.sleep(2)
 # 函数job3线程
 myThread(target=job3).start()
 time.sleep(2)
 threading.enumerate()
 print("线程枚举:",threading.enumerate())
 print("主线程:",threading.main_thread())

 print("线程id:",threading.get_ident())

result shown below:

在这里插入图片描述

5.reference

1.python多线程GIL,死锁等详解
2.python中Queue,conditon,异步线程使用


原文地址:https://blog.csdn.net/qq_37269626/article/details/142762556

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!