Python-多任务-线程

来源:互联网 发布:js的for循环执行顺序 编辑:程序博客网 时间:2024/06/04 00:07

创建线程

from threading import Threaddef test():    passt = Thread(target=test)t.start()

继承Thread来创建线程

from threading import Threadclass MyThread(Thread):    def run(self):        print(self.name)#self.name为默认线程namet = MyThread()t.start()

主线程会等待子线程结束后再结束

线程的执行顺序

不定

线程共享全局变量

互斥锁

threading.Lock

from threading import Lockl = Lock()#创建一把互斥锁,默认没有上锁l.acquire() #上锁,同一把锁只能上一次锁l.release() #释放锁

预防死锁

设置超时时间

mylock.acquire(timeout=2)#设置超时时间为2,超过2秒后则不去阻塞等待解锁

多个线程使用非共享变量

线程里的局部变量不共享

from threading import Threadimport threadingimport timedef test():    num = 100    if threading.cutrrent_thread()=="Thread-1":        num +=1    else:        time.sleep(2)    print(num)t1 = Thread(target=test)t2 = Thread(target=test)t1.start() #打印101t2.start() #打印100

扩展:队列Queue

使用队列来作为缓存

from queue import Queue #python3#from Queue import Queue python 2

用法与multiprocessing.Queue一样,但不可作为进程间的通信

全局ThreadLocal

全局ThreadLocal只在所属线程里共享

import threadingimport timelocal = threading.local()def test(name):    global local    local.name = name    time.sleep(1)    print(local.name)t1 = threading.Thread(target=test,("123",))t2 = threading.Thread(target=test,("456",))t1.start()#123t2.start()#456

GIL问题

Python的多线程是一个假的多线程,每次CPU只能执行一个线程,尽管是多核CPU也是这样.

例如:在双核CPU的电脑上运行双线程的程序,每次只能运行一个线程,那么就会使用两个CPU核来处理一条线程,Python解析器会不断切换线程来运行,故在外界眼里是两个线程是同时运行的

但是多进程却与多线程不同,若有多核CPU,运行多进程,每次都能同时运行多个进程

每个进程都会在其分配的CPU核里运行着,极大地利用了CPU的使用效率

故可以利用多进程来解决该问题

还可以利用C语言来解决该问题

这才是我们想要的嘛

在Python调用C动态库

首先写个函数(C是面向过程的嘛,把功能封装到函数里,再编译成库)

test.c

#include<stdio.h>void hello() {    printf("hello")}

在Linux编译成动态库

gcc -fPIC -shared test.c -o libtest.so-fPIC : 因为test.c里使用了stdio库,故需要该参数,该参数的用处:参考(知识涉及比较深,不用时报错了,使用了就没问题了)http://www.cnblogs.com/cswuyg/p/3830703.htmlhttp://blog.sina.com.cn/s/blog_54f82cc201011op1.html-shared : 用于生成动态库-o : 生成目标库(文件)的名字此时在当前目录下生成libtest.so库文件

在Python程序里

import ctypestest = ctypes.cdll.LoadLibrary("./libtest.so")#获取库对象test.hello() #直接调用使用库里的函数
原创粉丝点击