I.进程:

II.多线程threading总结

  threading用于提供线程相关的操作,线程是应用系统中工作的最小单位(cpu调用的最小单位).

  Python当前版本的多线程没有实现优先级,线程组,线程也不能被停止,暂停,恢复,中断.

  threading模块提供的类:

    Thread,Lock,Rlock,Condition,Semaphore,Event,Timer,local.

  threading 模块提供的常用方法:

    threading.currentThread()  :返回当前的线程变量.

    threading.enumerate()  :返回一个包含正在运行的线程的list.正在运行指线程启用后,结束前,不包含启动前和终止后的线程.

    threading.activeCount()  :返回正在运行的线程数量,与len(threading.enumerate())有相同的结果.

  threading 模块提供的常量:

    threading.TIMEOUT_MAX 设置threading全局超时时间.

 

Threading类

  Thread是线程类,有两种使用方法,直接传入要运行的方法或从Thread继承并覆盖run():

 1 import threading
 2 import time
 3 #方法一:将要执行的方法作为参数传给Thread的构造方法
 4 def action(arg):
 5     time.sleep(1)
 6     print 'the arg is:%s\r' %arg
 7 
 8 for i in xrange(4):
 9     t =threading.Thread(target=action,args=(i,))
10     t.start()
11 
12 print 'main thread end!'
13 
14 #方法二:从Thread继承,并重写run()
15 class MyThread(threading.Thread):
16     def __init__(self,arg):
17         super(MyThread, self).__init__()#注意:一定要显式的调用父类的初始化函数。
18         self.arg=arg
19     def run(self):#定义每个线程要运行的函数
20         time.sleep(1)
21         print 'the arg is:%s\r' % self.arg
22 
23 for i in xrange(4):
24     t =MyThread(i)
25     t.start()
26 
27 print 'main thread end!'
创建线程的两种方法

相关文章:

  • 2022-12-23
  • 2021-11-04
  • 2021-12-30
  • 2021-09-01
  • 2021-08-26
  • 2022-02-11
  • 2018-07-17
  • 2022-12-23
猜你喜欢
  • 2019-03-28
  • 2021-08-24
  • 2021-07-23
  • 2021-12-08
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案