python 使用 threading 实现多线程的例子

使用 threading.Thread实例化一个线程对象,传给threading.Thread的三个实参分别是:线程函数target、线程名称name、线程函数的实参(将所有实参打包在元祖中。只有一个参数的话,后面要加个逗号)。使用 Thread.start()启动线程的运行。Thread.join 表示等待该线程结束才运行到下一条指令。

这个例子包含三个线程,主线程启动两个子线程。主线程启动子线程之后,自己等待用户输入是否结束这个程序,输入等待是在一个循环的,每次先休眠1秒钟,在这一秒钟里,两个子线程运行,一旦等待用户输入时,整个程序挂起,这个好像不太符合人民的期待,可能需要使用c++语言的select机制,不知道python是不是有类似的东西。三个线程使用 lock= threading.Lock()来做同步。
这是线程函数thdfun.py:

import threading

thdContinue = True 
lock=threading.Lock() 

def listPop( seq ) :
    n1 = 0
    bContimue = True 
    while bContimue:
        n1 = n1 + 1 
        lock.acquire()
        bContimue = thdContinue 
        if  len( seq ) <  1  :
            lock.release()
            continue
        it = seq.pop(0)
        #lock.release()
        if n1 % 100 == 0 :
            print('in listPop', it )
        #print('in listPop', seq )
        lock.release()
    
def listAppend( seq ) :
    n = 100
    bContimue = True 
    while bContimue :
        n = n + 1
        lock.acquire()
        bContimue  = thdContinue 
        seq.append( n )
        if n % 100 == 0 :
            print( 'in append' ) #, seq ) 
        lock.release()

  这是主函数thdm.py:

import threading
import time 
import thdfun

def main() :
    print('thread %s is running...' % threading.current_thread().name)
    list1 = [] 
    t1 = threading.Thread(target=thdfun.listAppend, name='lAppend' , args = (list1,))
    t1.start()
    t2 = threading.Thread(target=thdfun.listPop, name='lPop' , args = (list1,))
    t2.start()
    
    while ( True ) :
        time.sleep( 1 )
        end = input("Exit? Y/N" )
        if end == 'Y' :
            thdfun.lock.acquire()
            thdfun.thdContinue = False
            thdfun.lock.release() 
            break ;


    t1.join()
    t2.join()
    print('thread %s ended.' % threading.current_thread().name)
main() 

猜你喜欢

转载自blog.csdn.net/brooknew/article/details/80813832