【问题标题】:Running multithreaded code after Queue.task_done()在 Queue.task_done() 之后运行多线程代码
【发布时间】:2019-04-09 10:48:26
【问题描述】:

在经典的“线程/队列”应用程序中。我需要在我的“消费者”功能中做进一步的计算。 Queue 为空后,在 urls.task_done() 之后不再执行任何代码。

我正在从 JSON api 导入市场数据并将其导入我的 MariaDB 数据库。 在 API 上,我要获取的每个项目都有一个自己的 url,所以我正在为函数中的所有可用 url 创建一个队列。 “消费者”功能根据我的数据库中已有的数据处理导入一组新数据或更新现有条目的队列。我已经尝试将实际的 while True 循环包装到它自己的函数中,但它对我不起作用。

def create_url():
    try:
        mariadb_connection = mariadb.connect(host='host
                                             database='db',
                                             user='user',                                             
                                           password='pw')

        cursor = mariadb_connection.cursor()

        cursor.execute('SELECT type_id from tbl_items')
        item_list = cursor.fetchall()
        print("Create URL - Record retrieved successfully")

        for row in item_list:

            url = 'https://someinternet.com/type_id=' + \
                str(row[0])
            urls.put(url)

        return urls

    except mariadb.Error as error:
        mariadb_connection.rollback()  
        print("Failed retrieving itemtypes from tbl_items table 
        {}".format(error))

    finally:
        if mariadb_connection.is_connected():
            cursor.close()
            mariadb_connection.close()

def import(urls):
    list_mo_esi = []
    try:
        mariadb_connection = mariadb.connect(host='host',
                                             database='db',
                                             user='user',
                                             password='pw')

        cursor = mariadb_connection.cursor()

        while True:
            s = requests.Session()
            retries = Retry(total=5, backoff_factor=1, status_forcelist=[502, 503, 504])
            s.mount('https://', HTTPAdapter(max_retries=retries))
            jsonraw = s.get(urls.get())
            jsondata = ujson.loads(jsonraw.text)

            for row in jsondata:
                cursor.execute('SELECT order_id from tbl_mo WHERE order_id = %s',
                               (row['order_id'], ))
                exists_mo = cursor.fetchall()
                list_mo_esi.append(row['order_id'])

                if len(exists_mo) != 0:
                    print("updating order#", row['order_id'])
                    cursor.execute('UPDATE tbl_mo SET volume = %s, price = %s WHERE order_id = %s',
                                   (row['volume_remain'], row['price'], row['order_id'], ))
                    mariadb_connection.commit()
                else:
                        cursor.execute('INSERT INTO tbl_mo (type_id, order_id, ordertype,volume, price) VALUES (%s,%s,%s,%s,%s)',
                                       (row['type_id'], row['order_id'], row['is_buy_order'], row['volume_remain'], row['price'], ))
                        mariadb_connection.commit()

            urls.task_done()

    except mariadb.Error as error:
        mariadb_connection.rollback()  
        print("Failed retrieving itemtypes from tbl_items table {}".format(error))

我的函数的以下 finally 部分没有执行,但应该执行。

    finally:
        list_mo_purge = list(set(list_mo_sql)-set(list_mo_esi))
        cursor.execute('SELECT order_id FROM tbl_mo')
        list_mo_sql = cursor.fetchall()
        print(len(list_mo_esi))
        print(len(list_mo_sql))

        if mariadb_connection.is_connected():
            cursor.close()
            mariadb_connection.close()

主线程

for i in range(num_threads):
    worker = Thread(target=import_mo, args=(urls,))
    worker.setDaemon(True)
    worker.start()

create_url()

urls.join()

所有任务完成后,我的工作人员在 urls.task_done() 之后立即停止执行代码。 但是,我需要在函数 urls.task_done() 之后执行更多代码以关闭数据库连接并从旧条目中清理我的数据库。我怎样才能使这个“最终”部分运行?

【问题讨论】:

  • mariadb.Error 提出来了吗?
  • 不,不是。线程只是停止正常,没有错误消息。

标签: python mysql queue python-multithreading


【解决方案1】:

你并没有中断。

您应该执行以下操作:

if urls.empty():
    break

您的import 线程很可能在urls.get() 处被阻塞

【讨论】:

  • 成功了。我的代码现在在 urls.task_done() 之后执行。至于导入块:是的,我注意到了,我现在在工作线程启动之前调用了 create_url() 。但是现在我收到一些错误消息,当提高线程数高于 1 时。必须深入研究它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 2022-11-11
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 2015-01-25
相关资源
最近更新 更多