【问题标题】:How do I itreate between X number of threads endlessly如何在 X 个线程之间无休止地迭代
【发布时间】:2019-01-22 16:08:39
【问题描述】:

我正在读取 1 到 4 个设备,我连接到每个设备并启动一个线程来读取数据。 我想创建一个运行线程 unit1、unit2 等然后再次启动的 while 循环。我都需要设置一个计时器,每 5 秒读取一次所有设备。

我的代码用于读取和发送数据我在理解如何创建一个 while 循环来永久读取单位时遇到问题。

thread_list = []
ports = ['/dev/ttyXRUSB0']
for item in ports:
  #setup conection  
  client = EPsolarTracerClient(method = 'rtu', port = item, baudrate = 115200, timeout = 0.2 )
  #client = ModbusClient(method = 'rtu', port = item, baudrate = 115200, timeout = 0.2 )
  client.connect()
  #read config from device
  epstime = client.read_rtc()
  sync_date = datetime.datetime.now()

  #write config to device
  client.write_rtc(sync_date)

  #create and start thread for device
  thread = threading.Thread(target=readunit,args=(client,))
  thread_list.append(thread)
  thread.start()
  # below is just leftover from old code but it is where i want to start the loop 
while client.connect:
  # readunit(client) # old code

   sleepTime = 5

   sleep(sleepTime)

我需要每 X 秒运行一次每个线程。并重复 永远.. 例如

线程1 线程2 …… 睡眠 x 秒。 重复

【问题讨论】:

    标签: python multithreading python-2.7


    【解决方案1】:

    我建议创建2个单独的函数并将它们线程化,然后在5秒后使用Timer函数调用它们,像这样,

    from threading import *
    import time
    
    def function1():
        while(True):
            print "1"
            time.sleep(5) # wait 5 seconds      
    
    def function2():
        while(True):
            print "2"
            time.sleep(5) # wait 5 seconds
    
    # create threads
    t = Timer(5.0, function1) # start the thread after 5 seconds
    t2 = Timer(5.0, function2)
    

    【讨论】:

    • 更改为线程来处理并在函数中创建while循环。现在可以了
    猜你喜欢
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    相关资源
    最近更新 更多