美文网首页
python的多线程类变量共享

python的多线程类变量共享

作者: Time一柒 | 来源:发表于2022-08-22 10:45 被阅读0次

    问题说明

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

    • 通过self调用方法名,多个线程之间类变量也是共享的,因为相当于在同一个空间下启动了多个不同函数,其他线程对某个类变量进行了修改,则其他线程会同步这个修改
    • 通过类名调用方法,相当于重新实例化了一个新的类,类变量不同线程之间不互通
    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
    

    相关文章

      网友评论

          本文标题:python的多线程类变量共享

          本文链接:https://www.haomeiwen.com/subject/vxxggrtx.html