Python中线程与进程的区别

  介绍

本篇文章为大家展示了Python中线程与进程的区别,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

<强> Python线程与进程

线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

<强>使用螺纹模块

方法一:

import 线程   import 时间   def  foo (n):   ,,,print (& # 39; foo  % & # 39; % n)   ,,,time . sleep (1)   ,,,print(& # 39;最终获得foo # 39;)   def 酒吧(n):   ,,,print (& # 39; bar  % & # 39; % n)   ,,,time . sleep (2)   ,,,print(& # 39;最终获得酒吧# 39;)   时间=t1  threading.Thread(目标=foo, arg游戏=(1))   目标==t2  threading.Thread(酒吧,,arg游戏=(2))   t1.start ()   t2.start ()   打印(& # 39;........拷贝,主要.......... & # 39;)

运行结果:

foo  1   bar  2   ........拷贝,主要..........   最终获得foo   最终获得酒吧

方法二:

import 时间、线程   class  MyThread (threading.Thread):   ,,,def  __init__(自我,,num):   ,,,,,,,threading.Thread.__init__(自我)   ,,,,,,,self.num =num   ,,,def 运行(自我):,,,,,,,,,,,,,#定义线程要运行的函数   ,,,,,,,印刷(“running 提醒号码:% s", %, self.num)   ,,,,,,,time . sleep (3)   if  __name__ ==, & # 39; __main__ # 39;:   ,,,t1 =, MyThread (1)   ,,,t2 =, MyThread (2)   ,,,t1.start ()   ,,,t2.start ()

运行结果:

running 提醒号码:1   running 提醒数量:2

加入方法使得主线程等待子线程完成才继续

import 线程   import 时间   时间=begin  time.time ()   def  foo (n):   ,,,print (& # 39; foo  % & # 39; % n)   ,,,time . sleep (1)   ,,,print(& # 39;最终获得foo # 39;)   def 酒吧(n):   ,,,print (& # 39; bar  % & # 39; % n)   ,,,time . sleep (2)   ,,,print(& # 39;最终获得酒吧# 39;)   时间=t1  threading.Thread(目标=foo, arg游戏=(1))   目标==t2  threading.Thread(酒吧,,arg游戏=(2))   t1.start ()   t2.start ()   t1.join ()   t2.join ()   打印(& # 39;........拷贝,主要.......... & # 39;)

运行结果:

foo  1   bar  2   最终获得foo   最终获得酒吧   ........拷贝,主要..........

在计算密集型任务中串行与多线程进行对比

import 线程、时间   时间=begin  time.time ()   def 添加(n):   ,,,sum =0   ,,,for 小姐:拷贝范围(n):   ,,,,,,sum  +=,我   ,,,印刷(总和)   添加(100000000)   添加(200000000)   最终获得=,time.time ()   打印(end-begin)

运行结果:

4999999950000000   19999999900000000   17.66856598854065
 4999999950000000
  19999999900000000
  21.088160276412964
  #,结果为串行运行比多线程运行更快

Cpython中有吉尔(全局解释器锁,全局解释器锁),所以在同一时刻,只能有一个线程进入调度。如果任务是IO密集型的,可以使用多线程;如果任务是计算密集型的,最优方法是改成c .

<强> setDaemon()

调用该方法只要是主线程完成,不管子线程是否完成都要和主线程一起退出。

<强> threading.currentThread()

返回当前的线程变量。

<强> threading.active_count()

返回正在运行的线程数量。

import 线程、时间   得到time  import , ctime睡眠   def 音乐(函数):   ,,,print (threading.current_thread ())   ,,,for 小姐:拷贝范围(2):   ,,,,,,,印刷(“Begin  listening 用% s只% s", % (func, ctime ()))   ,,,,,,,睡觉(2)   ,,,,,,,印刷(“最终获得listening  % s", % ctime ())   def 电影(函数):   ,,,print (threading.current_thread ())   ,,,for 小姐:拷贝范围(2):   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

Python中线程与进程的区别