当前位置:首页 » 编程语言 » python线程超时

python线程超时

发布时间: 2023-07-26 15:18:59

1. 为什么python多线程这么慢

差不多是这样子。多线程目前仅用于网络多线程采集, 以及性能测试。

其它的语言也有类似的情况,线程本身的特点导致线程的适用范围是受限的。只有CPU过剩,而其它的任务很慢,此时用线程才是有益的,可以很好平衡等待时间,提高并发性能。

线程的问题主要是线程的安全稳定性。线程无法强制中止,同时线程与主进程共享内存,可能会影响主进程的内存管理。

在python里线程出问题,可能会导致主进程崩溃。 虽然python里的线程是操作系统的真实线程。

那么怎么解决呢?通过我们用进程方式。子进程崩溃后,会完全的释放所有的内存和错误状态。所以进程更安全。 另外通过进程,python可以很好的绕过GIL,这个全局锁问题。

但是进程也是有局限的。不要建立超过CPU总核数的进程,否则效率也不高。

简单的总结一下。
当我们想实现多任务处理时,首先要想到使用multiprocessing, 但是如果觉着进程太笨重,那么就要考虑使用线程。 如果多任务处理中需要处理的太多了,可以考虑多进程,每个进程再采用多线程。如果还处理不要,就要使用轮询模式,比如使用poll event, twisted等方式。如果是GUI方式,则要通过事件机制,或者是消息机制处理,GUI使用单线程。

所以在python里线程不要盲目用, 也不要滥用。 但是线程不安全是事实。如果仅仅是做几个后台任务,则可以考虑使用守护线程做。如果需要做一些危险操作,可能会崩溃的,就用子进程去做。 如果需要高度稳定性,同时并发数又不高的服务。则强烈建议用多进程的multiprocessing模块实现。

linux或者是unix里,进程的使用代价没有windows高。还是可以接受的。

2. python 多线程如何延时

importtime
fromthreadingimportThread

##定时输入
classk(object):
x=0
sleepTime=0
def__init__(self,sleepTime=0):
self.sleepTime=sleepTime
self.input_delay_test()
definput_delay(self):
self.x=input("pleaseinput ")
definput_delay_test(self):
thd=Thread(target=self.input_delay)
thd.daemon=True
thd.start()
time.sleep(self.sleepTime)
print(self.x,self.sleepTime,sep='')
[print(x,end='')forxinrange(10)]

k(4)

3. 求助python多线程,执行到100多个停止了

python 线程 暂停, 恢复, 退出
我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦start后, 线程就属于失控状态. 不过, 我们可以自己实现这些. 一般的方法就是循环地判断一个标志位, 一旦标志位到达到预定的值, 就退出循环. 这样就能做到退出线程了. 但暂停和恢复线程就有点难了, 我一直也不清除有什么好的方法, 直到我看到threading中Event对象的wait方法的描述时.
wait([timeout])
Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.
阻塞, 直到内部的标志位为True时. 如果在内部的标志位在进入时为True时, 立即返回. 否则, 阻塞直到其他线程调用set()方法将标准位设为True, 或者到达了可选的timeout时间.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
当给定了timeout参数且不为None, 它应该是一个浮点数,以秒为单位指定操作的超时(或是分数)。
此方法在退出时返回内部标志,因此除非给定了超时且操作超时,否则它将始终返回True。
Changed in version 2.7: Previously, the method always returned None.
2.7版本以前, 这个方法总会返回None.
<br>
利用wait的阻塞机制, 就能够实现暂停和恢复了, 再配合循环判断标识位, 就能实现退出了, 下面是代码示例:
#!/usr/bin/env python
# coding: utf-8
import threading
import time
class Job(threading.Thread):
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__flag = threading.Event() # 用于暂停线程的标识
self.__flag.set() # 设置为True
self.__running = threading.Event() # 用于停止线程的标识
self.__running.set() # 将running设置为True
def run(self):
while self.__running.isSet():
self.__flag.wait() # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
print time.time()
time.sleep(1)
def pause(self):
self.__flag.clear() # 设置为False, 让线程阻塞
def resume(self):
self.__flag.set() # 设置为True, 让线程停止阻塞
def stop(self):
self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话
self.__running.clear() # 设置为False
下面是测试代码:
a = Job()
a.start()
time.sleep(3)
a.pause()
time.sleep(3)
a.resume()
time.sleep(3)
a.pause()
time.sleep(2)
a.stop()
<br>
测试的结果:
这完成了暂停, 恢复和停止的功能. 但是这里有一个缺点: 无论是暂停还是停止, 都不是瞬时的, 必须等待run函数内部的运行到达标志位判断时才有效. 也就是说操作会滞后一次.
但是这有时也不一定是坏事. 如果run函数中涉及了文件操作或数据库操作等, 完整地运行一次后再退出, 反而能够执行剩余的资源释放操作的代码(例如各种close). 不会出现程序的文件操作符超出上限, 数据库连接未释放等尴尬的情况.

4. python中requests请求超时 异常怎么书写

超时
你可以告诉requests在经过以timeout参数设定的秒数时间之后停止等待响应:
>>>requests.get('http://github.com',timeout=0.001)
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<mole>
requests.exceptions.Timeout:HTTPConnectionPool(host='github.com',port=80):Requesttimedout.(timeout=0.001)

用异常处理获取超时异常就可以了,给你个例子,自己修改既可以

try:
requests.get('https://www.taobao.com/',timeout=0.1)
exceptrequests.exceptions.ConnectTimeout:
NETWORK_STATUS=False
exceptrequests.exceptions.Timeout:
REQUEST_TIMEOUT=TRUE

5. python3套接字udp设置接受数据超时

Sometimes,you need to manipulate the default values of certain properties of a socket library, for example, the socket timeout.

设定并获取默认的套接字超时时间。

1.代码

1 import socket
2
3
4 def test_socket_timeout():
5 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6 print("Default socket timeout: %s" % s.gettimeout())
7 # 获取套接字默认超时时间
8 s.settimeout(100)
9 # 设置超时时间
10 print("Current socket timeout: %s" % s.gettimeout())
11 # 读取修改后的套接字超时时间
12
13
14 if __name__ == '__main__':
15 test_socket_timeout()
2. AF_INET和SOCK_STREAM解释

1 # 地址簇
2 # socket.AF_INET IPv4(默认)
3 # socket.AF_INET6 IPv6
4 # socket.AF_UNIX 只能够用于单一的Unix系统进程间通信
5
6 # socket.SOCK_STREAM(数据流) 提供面向连接的稳定数据传输,即TCP/IP协议.多用于资料(如文件)传送。
3.gettimeout()和settimeout()解释

1 def gettimeout(self): # real signature unknown; restored from __doc__
2 """
3 gettimeout() -> timeout
4
5 Returns the timeout in seconds (float) associated with socket
6 operations. A timeout of None indicates that timeouts on socket
7 operations are disabled.
8 """
9 return timeout
10
11
12 def settimeout(self, timeout): # real signature unknown; restored from __doc__
13 """
14 settimeout(timeout)
15
16 Set a timeout on socket operations. 'timeout' can be a float,
17 giving in seconds, or None. Setting a timeout of None disables
18 the timeout feature and is equivalent to setblocking(1).
19 Setting a timeout of zero is the same as setblocking(0).
20 """
21 pass
22 # 设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。
23 # 一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
4.运行结果

1 Default socket timeout: None
2 Current socket timeout: 100.0

6. python如何设置超时重新运行

python通过subprocess模块调用系统命令。实际使用中,有一次是命令进入了交互模式,结果web端直接卡死了。
调用时设置一个超时时间,时间用完后自动断开。
这样就避免了系统因为调用命令而僵死的问题。

7. python中主线程怎样捕获子线程的异常

最近因为别的需求,写了一个模块,似乎在这里能用得上:

https://github.com/SakuraSa/ChatProcess


其中的 example.py :

#!/usr/bin/envpython
#coding=utf-8

"""
example
"""

__author__='Rnd495'

fromtimeimportsleep
fromChatProcessimportChatroom


classEcho(Chatroom):
"""
Echo
"""
defresponse(self,data):
ifdata.startswith('sleep'):
sec=float(data[6:])
sleep(sec)
return'wakeupafter%dms'%(sec*1000)
elifdata:
returndata
else:
self.stop()
return'goodbye'


if__name__=='__main__':
,ProcessError

print'process01:'
e=Echo.create_process(lifetime=1).start()
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:0.1'),e.remain
printe.chat(''),e.remain

print''
print'process02:'
e=Echo.create_process(lifetime=1).start()
try:
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:1.0'),e.remain
printe.chat(''),e.remain
exceptTimeoutError,error:
print'error:',error

print''
print'process03:'
e=Echo.create_process(lifetime=1).start()
try:
printe.chat('Helloworld!'),e.remain
printe.chat('sleep:notanum'),e.remain
printe.chat(''),e.remain
exceptProcessError,error:
print'error:',error


运行结果为:

process01:
Helloworld!0.773000001907
wakeupafter100ms0.549000024796
goodbye0.547000169754

process02:
Helloworld!0.868000030518
error:TimeoutError

process03:
Helloworld!0.868000030518
error:('Erroroccurredonloop',ValueError('couldnotconvertstringtofloat:notanum',))


在其中的 process01 中,主进程捕获了 超时

在其中的 process02 中,主进程捕获了 子进程的错误


不知道你能不能用得上

8. 怎么设置python requests的超时时间

方法里有timeout参数,单位是秒:
requests.get(timeout=60)

如果解决了您的问题请采纳!
如果未解决请继续追问!

热点内容
如何配置二良腌料 发布:2025-02-07 16:11:54 浏览:735
数据库课程设计学生管理系统 发布:2025-02-07 16:11:50 浏览:764
美国文化密码是什么 发布:2025-02-07 16:07:14 浏览:261
安卓手机下雪特效怎么p 发布:2025-02-07 15:49:30 浏览:319
轮胎存储铭牌 发布:2025-02-07 15:43:38 浏览:74
防盗锁编程 发布:2025-02-07 15:31:33 浏览:860
安卓如何快速选择图片 发布:2025-02-07 15:30:43 浏览:468
硬件组态为什么不能编译 发布:2025-02-07 15:30:43 浏览:43
红帆oa服务器地址查询 发布:2025-02-07 14:31:41 浏览:657
文本框脚本图片 发布:2025-02-07 14:23:28 浏览:231