Python线程

2019-01-17  本文已影响0人  Dalvik_

线程的创建

1.通过创建Thread类指定target来实现

from threading import Thread
import time

def test():
    print("----------1-------")
    time.sleep(1)

for i in range(5):
    t = Thread(target=test)
    t.start()

2.通过继承Thread类重写run方法来实现

from threading import Thread
import time

def test():
    print("----------1-------")
    time.sleep(1)

class MyThread(Thread):
    def run(self):
        test()
for i in range(5):
    t = MyThread()
    t.start()

3.同一个进程中的线程之间共享全局变量

线程与进程的区别

定义的不同

互斥锁

#创建锁
mutex = threading.Lock()
#锁定
mutex.acquire([blocking])
#释放
mutex.release()

死锁

避免死锁的方式
1.上锁添加超时时间

mutex = Lock()
mutex.acquire(timeout=3)

2.银行家算法

生产者与消费者模式

#encoding=utf-8
import threading
import time

#python2中
from Queue import Queue

#python3中
# from queue import Queue

class Producer(threading.Thread):
    def run(self):
        global queue
        count = 0
        while True:
            if queue.qsize() < 1000:
                for i in range(100):
                    count = count +1
                    msg = '生成产品'+str(count)
                    queue.put(msg)
                    print(msg)
            time.sleep(0.5)

class Consumer(threading.Thread):
    def run(self):
        global queue
        while True:
            if queue.qsize() > 100:
                for i in range(3):
                    msg = self.name + '消费了 '+queue.get()
                    print(msg)
            time.sleep(1)


if __name__ == '__main__':
    queue = Queue()

    for i in range(500):
        queue.put('初始产品'+str(i))
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(5):
        c = Consumer()
        c.start()

队列就是用来给生产者和消费者解耦的

ThreadLocal

import threading

# 创建全局ThreadLocal对象:
local_school = threading.local()


def process_student():
    # 获取当前线程关联的student:
    std = local_school.student
    print('Hello, %s (in %s)' % (std, threading.current_thread().name))


def process_thread(name):
    # 绑定ThreadLocal的student:
    local_school.student = name
    process_student()


t1 = threading.Thread(target=process_thread, args=('dongGe',), name='Thread-A')
t2 = threading.Thread(target=process_thread, args=('老王',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()

异步

from multiprocessing import Pool
import time
import os


def test():
    print("---进程池中的进程---pid=%d,ppid=%d--" % (os.getpid(), os.getppid()))
    for i in range(3):
        print("----%d---" % i)
        time.sleep(1)
    return "hahah"


def test2(args):
    print("---callback func--pid=%d" % os.getpid())
    print("---callback func--args=%s" % args)


pool = Pool(3)
pool.apply_async(func=test, callback=test2)

time.sleep(5)

print("----主进程-pid=%d----" % os.getpid())

GIL 全局解释器锁

python解释器在解释python程序时,多线程的任务会存在GIL问题,也就是多线程执行时实际是只有单线程会占用CPU,多核CPU并不会同时执行多线程的程序。
避免GIL问题的方式:
1.采用多进程来实现多任务
2.采用C语言来实现多线程任务

把一个c语言文件编译成一个动态库的命令(linux平台下):
gcc xxx.c -shared -o libxxxx.so
from ctypes import *
from threading import Thread

#加载动态库
lib = cdll.LoadLibrary("./libdeadloop.so")

#创建一个子线程,让其执行c语言编写的函数,此函数是一个死循环
t = Thread(target=lib.DeadLoop)
t.start()

#主线程,也调用c语言编写的那个死循环函数
#lib.DeadLoop()

while True:
    pass
上一篇 下一篇

猜你喜欢

热点阅读