python多线程执行同一个函数_如何在Python中多线程/多处理一个特定函数的一个实例?...

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:17   2002   0

我认为你不需要线程,但我可能会误解你的要求,所以我将提出2个替代方案.

>没有线程和睡眠

假设您当前的程序流程如下:

while True:

data = read_sensors()

command = process(data)

motor_do(command)

time.sleep(delay)

然后你可以删除睡眠,如果最后一次呼叫至少延迟几秒钟,则只调用motor_do.

last_call_time = -delay # to be sure that motor_do can be called the first time

# "On Windows, [time.clock] returns wall-clock seconds elapsed since the first call to this

# function, as a floating point number, based on the Win32 function QueryPerformanceCounter()

# The resolution is typically better than one microsecond." (python 2.7 doc)

# i.e. close to 0 on first call of time.clock()

while True:

data = read_sensors()

command = process(data)

motor_try(command)

def motor_try(command):

global last_call_time

current_time = time.clock()

# on win that works, on unix... you may want to take a look at the NB

elapsed = current_time - last_call_time

if elapsed >= delay:

motor_do(command)

last_call_time = current_time

>使用线程(这是一个例子,我没有使用python 2.7进行线程/异步的经验,所以可能有更好的方法来做到这一点)

假设您当前的程序流程如下:

while True:

data = read_sensors()

command = process(data)

motor_do(command) // this function sleeps and you CANNOT change it

然后你必须启动1个线程,它只会异步地将命令推送到电机.

import thread

command = None

command_lock = thread.allocate_lock()

def main():

thread.start_new_thread(motor_thread)

global command

while True:

data = read_sensors()

with command_lock:

command = process(data)

def motor_thread():

while True:

while not command: # just to be sure

time.sleep(0.01)

# small delay here (for instance, the time consumed by read_sensors + process)

with command_lock:

motor_do(command)

command = None

time.sleep(delay)

注意:在Unix上,time.clock()返回处理器时间(=没有空闲时间),所以最好使用time.time()…除非更改系统时钟:“此函数通常返回非 – 如果在两次调用之间设置了系统时钟,则它可以返回比前一次调用更低的值.“ (python 2.7 doc)

我不知道time.sleep()对系统时钟变化的反应.

Python3:只使用time.monotonic()…或time.perf_counter().

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP