python中的多线程循环?

时间:2019-09-09 18:58:56

标签: python

我试图了解Python中的线程。我看过文档和示例,但坦率地说,许多示例过于复杂,我难以理解它们。

您如何清楚地显示为多线程而划分的任务?

2 个答案:

答案 0 :(得分:0)

我将使您的函数保持不变,但不是确保日期与字符串匹配,而是创建一个日期对象,并使用方法来标识它满足所需的条件,即day = 9和hour = 9。

示例:

vpRows := reflect.ValueOf(rows)                    // rows is a *sql.Rows
vRows := reflect.Indirect(vpRows)                  // now we have the sql.Rows struct
mem := vRows.FieldByName("lastcols")               // unexported field lastcols
unsafeLastCols := unsafe.Pointer(mem.UnsafeAddr()) // Evil
plastCols := (*[]driver.Value)(unsafeLastCols)     // But effective

for rows.Next() {
    rowVals := *plastCols
    fmt.Println(rowVals)
}

要使它们同时执行,您可以使用多线程在单独的线程上执行逻辑。

我还没有在python中使用多线程,但是这里有一个入门教程:An intro to Multi Threading

这是主要的python文档参考:Threading Module

希望这会有所帮助。干杯!

修改

要添加线程:

today =  datetime.datetime.now()

if today.day == 9 and today.hour == 9 and today.minute == 15:
   # perform your logic
else:
   pass

存储结果中返回的线程对象是一种冗余,但是出于演示目的,它可能有助于了解正在发生的事情。本质上,一旦功能 import threading import datetime cities = ['tokyo','london','regina'] news = [] def check_news(city, news): # your logic you want to perform per city. news.append(f"The city, {city}, news was checked. Nothing new.") return True def perform_action(): today = datetime.datetime.now() results = {} if today.day == 9 and today.hour == 9 and today.minute == 15: for c in cities: results[c] = threading.Thread(target=check_news, args=(c,news,)) #fire function to check news for target city results[c].start() #start thread else: pass return results value = perform_action() print(value) # >>> {'tokyo': <Thread(Thread-1, stopped 9368)>, 'london': <Thread(Thread-2, stopped 16860)>, 'regina': <Thread(Thread-3, stopped 2788)>} print(news) # >>> ['The city, tokyo, news was checked. Nothing new.', 'The city, london, news was checked. Nothing new.', 'The city, regina, news was checked. Nothing new.'] 完成,您将拥有一个包含每个城市新闻的数组。

我建议您检查此链接,以找到另一种方法来存储线程处理过程返回的值。 Multi-results-query

答案 1 :(得分:0)

这个问题尚不清楚,但是由于我假设您想对时区做一些事情,所以我建议这样做:

from datetime import datetime
from time import sleep

cities = [tokyo,newyork,beijing]


date = '09 09:00:00'
running = True
today = [None] * len(cities)
while running:
    for i in range(len(cities)):
        #today[i]=datetime.today().strftime("%d %H:%M:%S") # this would be dependent on city?
        today[i] = '09 09:00:00'     #(reference)
    for i in range(len(cities)):
        if date == today[i]:
            (Logic)
            sleep(1000)
        else:
            pass

但是,如果您想在(逻辑)部分运行时继续刷新时间检查部分,则需要研究多线程。