Python基础8:线程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/plychoz/article/details/86659980

线程、守护线程、互斥锁


'''
线程:执行代码的分支,程序默认会有一个线程(主线程)
'''
import threading, time

def AA(count):
    for i in range(count):
        print('AA')
        time.sleep(0.3)

def BB(count):
    for i in range(count):
        print('BB')
        print(threading.current_thread().getName())


if __name__ =='__main__':
    #创建子线程(执行代码)
    sub_thread = threading.Thread(target = AA, args=(5,))
    three_thread = threading.Thread(target= BB, kwargs={'count':5})

    # 设置守护线程,主线程结束,子线程也结束
    sub_thread.setDaemon(True)
    #sub_thread = threading.Thread(target = AA, args=(5,), daemon= True)

    #启动线程
    #线程只能启动(调用)一次
    #线程执行没有顺序,跟cpu调度相关
    sub_thread.start()
    three_thread.start()

    #获取当前线程的名字
    print(threading.current_thread().getName())

    sub_thread.setName('bbbb')
    print(threading.current_thread().getName())

    #获取线程id(启动以后才有)
    print(threading.current_thread().ident)

    #判断线程是否存活
    print(threading.current_thread().is_alive())

    print(threading.active_count())

    #主线程等子线程结束之后,才会结束


#run()and start()
def work():
    count = 1
    while True:
        if count >=4:
            break
        time.sleep(1)
        count += 1
        print(threading.current_thread().name, threading.current_thread().ident)

t1 = threading.Thread(target=work)
t2 = threading.Thread(target=work)

t1.start()
t2.start()

#start()才会开启新线程,并调用run()
#run()实际上是将方法调用了一下,并没有开启线程

#重写
class MyThread(threading.Thread)
    def start(self):

        super(MyThread, self).start()



'''
互斥锁
资源竞争
有个全局变量,保证同一时刻只有一个线程去执行代码
'''
import threading

lock =threading.Lock()

g_num = 0

def AA():

    #上锁
    lock.acquire()
    global g_num
    for i in range(1000000):
        g_num +=1
    print('AA', g_num)

    #释放锁
    lock.release()

def BB():

    #上锁
    lock.acquire()
    global g_num
    for i in range(1000000):
        g_num +=1
    print('BB', g_num)

    #释放锁
    lock.release()

if __name__ == '__main__':
    ft = threading.Thread(target=AA)
    sc = threading.Thread(target=BB)

    ft.start()
    sc.start()

    #这个线程执行时,其他线程等待,保证g_num结果正确
    ft.join()
    sc.join()
    print(g_num)
'''
166525
AA 1342195
BB 1359639
'''

 

展开阅读全文

没有更多推荐了,返回首页