我对测试多处理模块感到有点困惑。
让我们模拟一个数字计时器。代码看起来像:
function checkUser(user){
var number = user.length;
if(number>10){
document.getElementById("username").style.borderColor = "red";
// <!-- document.getElementById("submit").disabled = true; Disable submit button -->`enter code here`
document.getElementById("maxReached").style.visibility = "visible";
}else {
document.getElementById("maxReached").style.visibility = "hidden";
document.getElementById("username").style.borderColor = "black";
}
}
正确返回:
<html>
<head>
</head>
<body>
<form action="">
Username: <input type="text"`enter code here` name="usrname" id="username" oninput="checkUser(this.value);" maxlength="15">
<label id="maxReached" style="visibility: hidden; color:red">Your title is too long</label><br>
<input type="submit" id="submit" value="Submit">
</form>
</body>
</html>
现在我想使用管道从我的虚拟外部数字时钟设备读取时钟:
start=datetime.now()
while True:
now=datetime.now()
delta=now-start
s = delta.seconds + delta.microseconds/1E6
print s
time.sleep(1)
它返回:
8e-06
1.001072
2.00221
3.003353
4.004416
...
这里的计时器似乎并没有在后台永久运行。&#34; Queue&#34;看起来像:
def ask_timer(conn):
start=datetime.now()
while True:
now=datetime.now()
delta=now-start
s = delta.seconds + delta.microseconds/1E6
conn.send(s)
parent_conn, child_conn = Pipe()
p = Process(target=ask_timer, args=(child_conn,))
p.start()
while True:
print parent_conn.recv()
time.sleep(1)
与管道一样。这只是我对python多处理的误解吗?我如何从正在运行的并行线程中实时询问值?
答案 0 :(得分:1)
一切正常。子进程完全独立于主进程执行ask_timer()
函数。你在这个函数中没有time.sleep()
,所以它只是在无限循环中打印或放入队列增量,间隔为10ms。
您的主要流程会在一秒钟内向子流程询问数据并获取数据。数据是这些小间隔之一。
问题在于,您需要将更多数据放入管道/队列,而不是从中获取数据。所以当你提问时,你会得到旧的数据。要测试你是否可以在循环中打印队列大小(不能在OS X上工作):
def ask_timer(q):
start = datetime.now()
while True:
now = datetime.now()
delta = now - start
s = delta.seconds + delta.microseconds / 1E6
q.put(s)
q = Queue()
p = Process(target=ask_timer, args=(q,))
p.start()
while True:
print q.get()
print q.qsize()
time.sleep(1)
队列大小会快速增长。
显然,您可以使用shared memory从子进程中读取当前值。
from multiprocessing import Process, Value
from datetime import datetime
import time
from ctypes import c_double
def ask_timer(v):
start = datetime.now()
while True:
now = datetime.now()
delta = now - start
s = delta.seconds + delta.microseconds / 1E6
v.value = s
val = Value(c_double, 0.0)
p = Process(target=ask_timer, args=(val,))
p.start()
while True:
print(val.value)
time.sleep(1)