I am try to get diffent instance of one class in mutil-thread, but the id(instance) retuned the same id random, Even if I add sleep time, this still happens, why?
#!/usr/bin/python
# coding=utf-8
import random
import threading
class Foo():
def __init__(self):
self.num = random.randrange(10000)
def __str__(self):
return "rand num is {}".format(self.num)
def getInatance():
if lock.acquire():
f = Foo()
print(id(f), f)
lock.release()
lock = threading.Lock()
if __name__ == "__main__":
for x in range(10):
th = threading.Thread(target=getInatance)
th.start()
for th in threading.enumerate():
if th is not threading.current_thread():
th.join()
# 2384808866048 rand num is 357
# 2384808640128 rand num is 7143
# 2384808640128 rand num is 900
# 2384808640128 rand num is 3260
# 2384808640032 rand num is 8161
# 2384808640032 rand num is 8573
# 2384808640080 rand num is 6300
# 2384808640080 rand num is 3476
# 2384808640128 rand num is 8112
# 2384808640128 rand num is 7357