python 多线程编程

import threading

#当前线程   打印线程名
t=threading.current_thread()
print(t.name)
#活动线程数
print(threading.active_count())
#当前主线程
t=threading.main_thread()
print(t.name)

创建可执行线程:

例1,

import threading
import time

def main():
    #线程对象t1
    t1=threading.Thread(target=thread_body) #线程体  name默认
    t1.start()#线程启动
    #线程2
    t2 = threading.Thread(target=thread_body)
    t2.start()
def thread_body():
    #当前线程对象
    t=threading.current_thread()
    for i in range(5):
        print(i,'次,执行',t.name)
        #当前线程休眠1秒,有了休眠  多线程才会交替执行
        time.sleep(1)
    print('{}完成'.format(t.name))
if __name__=='__main__':
    main()

结果:

例2:

import threading
import time
class my_thread(threading.Thread):
    def __init__(self,name=None):
        super().__init__(name=name)
    #重写run()
    def run(self):
        t = threading.current_thread()
        for i in range(5):
            print(i, '次,执行', t.name)
            time.sleep(1)
        print('{}完成'.format(t.name))


def main():
    t1=my_thread()
    t1.start()
    t2=my_thread(name='thread2')
    t2.start()



if __name__=='__main__':
    main()

线程管理

 jion等待:

import threading
import time
value=0
def thread_body():
    global value
    print('thread 开始')

    for i in range(2):
        print('循环执行')
        value +=1
        time.sleep(1)
    print('thread 结束')
def main():
    t1=threading.Thread(target=thread_body,name='T1')
    t1.start()

    t1.join()    #  等待t1结束,阻塞当前线程
    print(value)
    
if __name__=='__main__':
    main()

结果:

线程停止:

import threading
import time
value=True
def thread_body():
    global value
    print('thread 开始')

    while value:
        print('yunxing')
        time.sleep(3)
    print('thread 结束')
def main():
    global value
    t1=threading.Thread(target=thread_body,name='T1')
    t1.start()
    a=int(input('输入数字  按回车 结束进程'))
    if a>=0:
        value=False

if __name__=='__main__':
    main()

临界资源问题

出现的问题如下:

import threading
import time

class ticket():
    def __init__(self,count):
        self.ticket_count=count
    def get_count(self):
        return self.ticket_count
    def sell(self):
        #模拟等待用户付款
        time.sleep(1)
        print('{}号票已出'.format(self.ticket_count))
        self.ticket_count -=1

t=ticket(5) #实例化



def thread_body1():
    global t
    print('t1 开始')

    while True:
        curr_tick = t.get_count()
        if curr_tick>0:
            t.sell()
        else:
            break
    print('t1 结束')
def thread_body2():
    print('t2 开始')
    global t
    curr_tick = t.get_count()
    while True:
        curr_tick = t.get_count()
        if curr_tick > 0:
            t.sell()
        else:
            break
    print('t2 结束')


def main():
    t1=threading.Thread(target=thread_body1,name='T1')
    t1.start()
    t2 = threading.Thread(target=thread_body2, name='T1')
    t2.start()

if __name__=='__main__':
    main()

同时使用了3号票的数据

 

要使用   多线程同步

import threading
import time

class ticket():
    def __init__(self,count):
        self.ticket_count=count
    def get_count(self):
        return self.ticket_count
    def sell(self):
        #模拟等待用户付款
        time.sleep(1)
        print(threading.current_thread().name)
        print('{}号票已出'.format(self.ticket_count))

        self.ticket_count -=1

t=ticket(10) #实例化


# 创建lock
lock=threading.Lock()


def thread_body1():
    global t,lock

    print('t1 开始')

    while True:
        lock.acquire()#上锁
        curr_tick = t.get_count()
        if curr_tick>0:
            t.sell()

        else:
            lock.release()#解锁
            break
        lock.release()#解锁
        time.sleep(1)  #做到交替执行
    print('t1 结束')
def thread_body2():
    print('t2 开始')
    global t,lock

    while True:
        lock.acquire()
        curr_tick = t.get_count()
        if curr_tick > 0:
            t.sell()

        else:
            lock.release()#解锁
            break
        lock.release()#解锁
        time.sleep(3)#做到交替执行
    print('t2 结束')


def main():
    t1=threading.Thread(target=thread_body1,)
    t1.start()
    t2 = threading.Thread(target=thread_body2, )
    t2.start()

if __name__=='__main__':
    main()

结果:

线程间通信问题

堆栈 例子:

1.使用Condition()

import threading
import time

#!!!!!!创建条件变量!!!!!!!!!!
condition=threading.Condition()

class Stack:
    def __init__(self):
        #栈顶指针
        self.point=0
        #5个位置的栈
        self.data=[-1,-1,-1,-1,-1]
    #压栈
    def push(self,c):
        global condition
        condition.acquire()#加锁
        while self.point==len(self.data):  #栈满
            #等待其他线程  出栈
            condition.wait()
            #通知其他线程
            condition.notify()

        self.data[self.point]=c
        self.point +=1

        condition.release()#解锁
    #出栈
    def pop(self):
        global condition
        condition.acquire()
        # 堆栈无数据,不能出栈
        while self.point == 0:
            # 等待其他线程把数据压栈
            condition.wait()
            # 通知其他线程压栈
            condition.notify()

        self.point -=1
        out=self.data[self.point]
        condition.release()
        return out

S=Stack()
#添加线程体
def t_add():
    global S
    for i in range(9):
        S.push(i)
        print('压入',i)
        time.sleep(1)
def t_out():
    global S
    for i in range(9):
        x=S.pop()
        print('弹出',x)
        time.sleep(1)


def main():
    producer = threading.Thread(target=t_add)
    producer.start()
    consumer = threading.Thread(target=t_out)
    consumer.start()


if __name__=='__main__':
     main()

2.使用event()

import threading
import time

event=threading.Event()

class Stack:
    def __init__(self):
        #栈顶指针
        self.point=0
        #5个位置的栈
        self.data=[-1,-1,-1,-1,-1]
    #压栈
    def push(self,c):
        global event
        while self.point==len(self.data):  #栈满
            #等待其他线程  出栈
            event.wait()
            #通知其他线程
        event.set()

        self.data[self.point]=c
        self.point +=1

    #出栈
    def pop(self):
        global event
        # 堆栈无数据,不能出栈
        while self.point == 0:
            # 等待其他线程把数据压栈
            event.wait()
            # 通知其他线程压栈
        event.set()

        self.point -=1
        out=self.data[self.point]
        return out

S=Stack()
#添加线程体
def t_add():
    global S
    for i in range(9):
        S.push(i)
        print('压入',i)
        time.sleep(1)
def t_out():
    global S
    for i in range(9):
        x=S.pop()
        print('弹出',x)
        time.sleep(1)


def main():
    producer = threading.Thread(target=t_add)
    producer.start()
    consumer = threading.Thread(target=t_out)
    consumer.start()


if __name__=='__main__':
     main()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值