当前位置: 移动技术网 > IT编程>脚本编程>Python > python线程里哪种模块比较适合

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

2020年08月03日  | 移动技术网IT编程  | 我要评论

在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线程用什么模块好内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网