Skip to content

【疑问】面试2:实现单例模式 #2

@starYellow966

Description

@starYellow966

有一个疑问,通过 new 实现单例那段代码在多线程下运行还是做不到单例。比如线程 1 在执行完 if 语句且判 true 后,切换到线程 2 。线程 2 成功创建了一个实例。那么线程 1 再执行时又会创建一个实例。

import time

class SingleTon(object):
    _instance = {}
    def __new__(cls, *args, **kwargs):
        print(threading.current_thread())
        if cls not in cls._instance:
            print('Singleton __new__ is true')
            time.sleep(15)
            cls._instance[cls] = super(SingleTon, cls).__new__(cls, *args, **kwargs)

        return cls._instance[cls]

class Test(SingleTon):
    def __init__(self):
        print('test __init__')
        self.val = 2

def running():
    t1 = Test()
    print(id(t1))

import threading

th1 = threading.Thread(target=running, name='th1')
th2 = threading.Thread(target=running, name='th2')
th1.start()
th2.start()
##### 输出 #####
<Thread(th1, started 2736)>
Singleton __new__ is true
<Thread(th2, started 3728)>
Singleton __new__ is true
test __init__
2210173698000
test __init__
2210173726848

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions