Python——threading(线程模块)

创建和使用方式基本和进程一致。

有关线程的文字讲述,请见:计算机——进程&线程&协程

import time
from threading import Thread,current_thread,enumerate,active_count
 
def func(i1,i2):
    i = i1+i2
    time.sleep(0.5)
    print(current_thread())                     #查看线程的ID并以对象形式显示,适用于函数使用,
for i in range(5):
    t = Thread(target=func,args=(i,i*2))        #传值和进程一样,需要使用元组形式进行传输。
    t.start()                                   #启动也是需要使用start
    print(t.ident)                              #可以查看所创建的线程ID,可以用在面向对象中使用。
    t.daemon = True                             #创建守护线程。
print(enumerate())                              #可以看到正在运行的主线程和子线程。以对象法师呈现在列表当中。
print(active_count())                           #可以查看子线程的个数,包括主线程。

线程+锁的单例模式

from threading import Thread,Lock
 
class SingLeton(object):
    instance = None
    lock = Lock()
    def __new__(cls, *args, **kwargs):
        with cls.lock:
            if not cls.instance:
                cls.instance = object.__new__(cls)
        return cls.instance
for i in range(10):
    print(SingLeton())

 

posted @ 2022-04-12 16:03  新兵蛋Z  阅读(222)  评论(0)    收藏  举报