当前位置:首页 » python教程 » 正文

python线程里哪种模块比较适合

看: 683次  时间:2020-08-21  分类 : python教程

在Python中可使用的多线程模块主要有两个,thread和threading模块。thread模块提供了基本的线程和锁的支持,建议新手不要使用。threading模块允许创建和管理线程,提供了更多的同步原语。

thread模块函数:

  • start_new_thread(function, args[, kwargs]):启动新的线程以执行function,返回线程标识。
  • allocate_lock():返回LockType对象。
  • exit():抛出SystemExit异常,如果没有被捕获,线程静默退出。
  • LockType类型锁对象的方法:
  • acquire([waitflag]):无参数,无条件获得锁,如果锁已经被其他线程获取,则等待锁被释放。如果使用整型参数,参数为0,如果锁可获取,则获取且返回True,否则返回False;参数为非0,与无参数相同。
  • locked():返回锁的状态,如果已经被获取,则返回True,否则返回False。
  • release():释放锁。只有已经被获取的锁才能被释放,不限于同一个线程。
  • threading模块提供了更好的线程间的同步机制。threading模块下有如下对象:
  • Thread
  • Lock
  • RLock
  • Condition
  • Event
  • Semaphore
  • BoundedSemaphore
  • Timer
  • threading模块内还有如下的函数:
  • active_count()
  • activeCount():返回当前alive的线程数量
  • Condition():返回新的条件变量对象
  • current_thread()
  • currentThread():返回当前线程对象
  • enumerate():返回当前活动的线程,不包括已经结束和未开始的线程,包括主线程及守护线程。
  • settrace(func):为所有线程设置一个跟踪函数。
  • setprofile(func):为所有纯种设置一个profile函数。

内容扩展:

Python线程模块

常用参数说明

  • target 表示调用对象,几子线程要执行的的任务
  • name 子线程的名称
  • args 传入target函数中的位置参数,是一个元组,参数后必须加逗号

常用的方法

  • Thread.star(self)启动进程
  • Thread.join(self)阻塞进程,主线程等待
  • Thread.setDaemon(self,daemoic) 将子线程设置为守护线程
  • Thread.getName(self.name) 获取线程名称
  • Thread.setName(self.name) 设置线程名称
import time
from threading import Thread


def hello(name):
  print('hello {}'.format(name))
  time.sleep(3)
  print('hello bye')

def hi():
  print('hi')
  time.sleep(3)
  print('hi bye')

if __name__ == '__main__':

  hello_thread = Thread(target=hello, args=('wan zong',),name='helloname') #target表示调用对象。name是子线程的名称。args 传入target函数中的位置参数,是个元组,参数后必须加逗号
  hi_thread = Thread(target=hi)

  hello_thread.start() #开始执行线程任务,启动进程
  hi_thread.start()

  hello_thread.join() #阻塞进程 等到进程运行完成 阻塞调用,主线程进行等待
  hi_thread.join()

  print(hello_thread.getName())
  print(hi_thread.getName()) #会默认匹配名字

  hi_thread.setName('hiname')
  print(hi_thread.getName())

  print('主线程运行完成!')

到此这篇关于python线程里哪种模块比较适合的文章就介绍到这了,更多相关python线程用什么模块好内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!