首页 > 编程知识 正文

python线程安全,python创建多线程

时间:2023-05-05 09:42:23 阅读:151546 作者:4301

几个一般函数:

start () :启动线程活动。

threading.lock(:创建锁定

acquire () :线程锁定

释放(:解锁

返回threading.activeCount (:当前进程中的线程数(包括主进程) )

Threading.enumerate (:返回当前正在运行的thread对象的列表

threading.setDaemon (:如果将参数设置为True,则线程将被声明为守护程序线程。 start ) )必须在方法之前设置。 如果不设置为守护程序,它将无限挂起。

join ) )方法将在子进程运行完成后再运行父进程

我个人喜欢创建线程类以实现多线程是一个简单的例子,打开两个线程,打印时间,没有锁定

#-* -编码: utf-8-* -

导入标题

导入时间

类我的thread (threading.thread ) :

def __init__(self,threadID,name,counter ) :

super(mythread,self ).__init__ () )

self.threadID,self.name,self.counter=threadID,name,counter

defrun(self ) :

打印'进程开始: self.name

self.run_fun(self.name,self.counter,3 ) )。

打印'进程结束: ' self.name

efrun_fun(self,threadName,delay,counter ) :

while counter:

time.sleep(delay )

打印' % s : % s ' % (thread name,time.strftime (' % y-% m-% d % h : % m : % s ',time.localtime ) ) )

counter -=1

thread1=mythread(1,' thread-1 ',1 ) )。

thread2=mythread(2,' thread-2 ',2 ) )。

thread1.start (

thread2.start (

print threading.enumerate (

打印'主进程结束'

结果表明,线程1和线程2将同时运行

封锁情况

#-* -编码: utf-8-* -

导入标题

导入时间

类我的thread (threading.thread ) :

def __init__(self,threadID,name,counter ) :

super(mythread,self ).__init__ () )

self.threadID,self.name,self.counter=threadID,name,counter

defrun(self ) :

打印'进程开始: self.name

threadlock.acquire(#获取锁

self.run_fun ()

threadlock.release(#解锁

打印'进程结束: ' self.name

defrun_fun(self ) :

counter=3

while counter:

time.sleep(self.counter )

print'%s3360%s'%(self.name,time.strftime (' % y-% m-% d % h : % m : % s ',time.localtime ) ) )

counter -=1

threadLock=threading.Lock (

thread1=mythread(1,' thread-1 ',1 ) )。

thread2=mythread(2,' thread-2 ',2 ) )。

thread1.start (

thread2.start (

print threading.enumerate表示正在运行的线程

打印'主进程结束'

结果表明,加锁后,只有线程1运行后,线程2才能运行

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。