python基础——线程

学习Python线程:

Python3 线程中常用的两个模块为: 
_thread 
threading(推荐使用) 
thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用”thread” 模块。为了兼容性,Python3 将 thread 重命名为 “_thread”。

Python中使用线程有两种方式:函数或者用类来包装线程对象。

函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下

import threading
import time
def someting():
    for i in range(1,11):
        print(i)
        time.sleep(1)

threading._start_new_thread(someting(),())
print("main")

类方式:

class Mythread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        print("Mythread")
    def run(self):
        for i in range(1,11):
            print(i)
            time.sleep(1)
    def start(self):
        print("开始Mythread")
        super().start()


t=Mythread()
t2 = Mythread()
t.start()
t2.start()

如果重写了start一定要调用父类的start.run会在strat之后自动调用,join线程阻塞方法,那个线程调用那个线程阻塞。

线程锁: 

当多个线程同时进行任务时,为了保证不会有多个线程同时对同一个数据进行操作造成不可预料的后果,所以有了线程锁。 

生成一个锁:

lock = threading.Lock()cond = threading.Condition(lock=lock)

锁当然有上锁和未上锁两种状态,当一个线程要访问数据时,必须要先获得锁,如果已经有别的线程获得锁,那么就进入等待状态,等别的线程把锁释放后,再进行操作。 
下面是一个简单的线程锁代码:

import threading
import time
import random
class Thread1(threading.Thread):
    def run(self):
        for i in range(1,11):
            if i==3:  #当Thread1运行到3的时候进入
                cond.acquire() #锁
                cond.wait()  #等待Thread2运行完成
                cond.release() 
            print(i)
            time.sleep(1)


class Thread2(threading.Thread):
    def run(self):
        for i in range(30,19,-1):
            print(i)
            time.sleep(1)
        cond.acquire()
        cond.notify()  #唤醒
        cond.release()

lock = threading.Lock()
cond = threading.Condition(lock=lock)
t1 = Thread1()
t2 = Thread2()
t1.start()
t2.start()

有4个和尚,一个做饭的三个吃饭的。 
也就是经典的生产者和消费者,用到线程锁技术:

import threading
import time
import random
class Huofu(threading.Thread):
    def __init__(self,name=None):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        while True:
            cond.acquire()
            if len(guo)==0:
                for i in range(1,11):
                    guo.append(i)
                    print('做出第{0}个馒头'.format(i))
                    time.sleep(1)
                cond.notify_all()
                cond.release()
            cond2.acquire()
            cond2.wait()
            cond2.release()

class Chihuo(threading.Thread):
    def __init__(self,name=None):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        while True:
            mantou=None
            cond.acquire()
            if len(guo)==0:
                cond2.acquire()
                cond2.notify()
                cond2.release()
                cond.wait()
            else:
                mantou=guo.pop()
            cond.release()
            if mantou is not None:
                print('{0}正在吃{1}'.format(self.name,mantou))
                time.sleep(random.randint(1,5))

guo = []
lock = threading.Lock()
cond = threading.Condition(lock=lock)#吃的锁
lock2 = threading.Lock()
cond2 = threading.Condition(lock=lock2)#蒸馒头的锁
Huofu(name='做饭和尚').start()
Chihuo(name='长眉和尚吃饭').start()
Chihuo(name='短眉和尚吃饭').start()
Chihuo(name='中眉和尚吃饭').start()

猜你喜欢

转载自blog.csdn.net/pythonzyj/article/details/81054850