Python_多线程1(创建线程,简单线程同步)

threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:

  • threading.currentThread(): 返回当前的线程变量。
  • threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
  • threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

  • run(): 用以表示线程活动的方法。
  • start():启动线程活动。

     

  • join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
  • isAlive(): 返回线程是否活动的。
  • getName(): 返回线程名。
  • setName(): 设置线程名。

Thread.join():在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束,但是如果主线程处理完其他的事务后,需要用到子线程的处理结果,也就是主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。

简单的线程同步:访问临界资源时需要同步线程,Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,感觉像是互斥锁的感觉。

import threading
import time 

exitflag=0

global num
num=0
class myThread(threading.Thread):
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID=threadID
        self.name=name
        self.counter=counter
        self.lock=threading.Lock()
    def run(self):
        print("start:"+self.name)
        self.lock.acquire()
        global num
        for i in range(5):
            num+=1
            print("num:%d
"%(num))
        #print_time(self.name,self.counter,5)
        print(self.getName()+"
")
        self.lock.release()
        print("end:"+self.name+"
")

def print_time(threadName,delay,counter):
    while counter:
        if exitflag:
            threadName.exit()
        time.sleep(delay)
        print("%s: %s"%(threadName,time.ctime(time.time())))
        counter-=1
        
thread1=myThread(1,"Thread-1",1)
thread2=myThread(2,"Thread-2",2)
threads=[]

thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for i in threads:
    i.join()
print("exit main thread
")
原文地址:https://www.cnblogs.com/jasonlixuetao/p/6112246.html