‘壹’ python theading 如何结束线程
其实时,如果主线程退出的话,其它子线程就可退出。
如果你要某些线程在运行一个阀值自动退出,你可以在线程里面做一步运行时间检测(或者循环次数检测)。
‘贰’ python 多线程 运维问题, 详见问题补充 我写了一段代码 但感觉有问题,希望大侠能指点。
你这个脚本有些语法问题,不过总的设计思路是没有问题的。 我已经用你的脚本执行了,输入如下。我觉得可以讲hosts.txt文件拆分成5个文件,每个文件含8条ip,按顺序执行,这样可以控制每次只处理8个ip,也就达到并发8台机子的要求。
python multhred.py "echo 'hello world'"
Please input password:
current has 1 threads
current has 3 threads
current has 4 threads
current has 6 threads
current has 8 threads
current has 11 threads
current has 12 threads
current has 14 threads
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
‘叁’ 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知识请关注Python自学网