python的多线程类变量共享

2022-08-22  本文已影响0人  Time一柒

问题说明

在同一个类中启动多线程的方法,和多线程执行的方法如果都在同一个类中,启动多线程时

  1. 通过self调用
import logging
import threading
import time


class LabelService:

    def create_thread(self, task_id, collection_name_list):
        """
        :param task_id: 任务id
        :param collection_name_list: 集合名称列表
        """
        # 多线程处理数据
        for collection_name in collection_name_list:
            # 创建线程
            thread_processing_data = threading.Thread(
                target=self.processing_data,
                args=(task_id, collection_name))
            thread_processing_data.name = task_id + "data_push_" + collection_name
            # 启动线程
            thread_processing_data.start()
            print("创建线程:[" + thread_processing_data.getName() + "]" + str(thread_processing_data.is_alive()))

    def processing_data(self, task_id, collection_name):
        self.task_id = task_id
        self.collection_name = collection_name
        print(self.task_id + self.collection_name)
        if collection_name == "a":
            time.sleep(10)
        print(self.task_id + self.collection_name)
LabelService().create_thread("qqqqqqqqqqqqqq", ["a", "b"])

输出:
qqqqqqqqqqqqqqa
qqqqqqqqqqqqqqb
qqqqqqqqqqqqqqb
qqqqqqqqqqqqqqb
  1. 通过类名调用
import threading
import time
class LabelService:

    def create_thread(self, task_id, collection_name_list):
        """
        :param task_id: 任务id
        :param collection_name_list: 集合名称列表
        """
        # 多线程处理数据
        for collection_name in collection_name_list:
            # 创建线程
            thread_processing_data = threading.Thread(
                target=LabelService().processing_data,
                args=(task_id, collection_name))
            thread_processing_data.name = task_id + "data_push_" + collection_name
            # 启动线程
            thread_processing_data.start()

    def processing_data(self, task_id, collection_name):
        self.task_id = task_id
        self.collection_name = collection_name
        print(self.task_id + self.collection_name)
        if collection_name == "a":
            time.sleep(10)
        print(self.task_id + self.collection_name)
LabelService().create_thread("qqqqqqqqqqqqqq", ["a", "b"])

输出:
qqqqqqqqqqqqqqa
qqqqqqqqqqqqqqb
qqqqqqqqqqqqqqb
qqqqqqqqqqqqqqa
上一篇 下一篇

猜你喜欢

热点阅读