Python编程:threading多线程

进程process:应用程序以一个整体的形式暴露给操作系统管理,里边包含对各种资源的调用,内存的分配,对各种资源管理的集合


线程thread:操作系统最小的调度单位,是一串指令的集合


进程 要操作cpu,必须先创建一个线程


进程与线程区别:线程共享,进程独立

线程共享内存空间,进程内存是独立的

同一个进程之间的线程可以直接通信,两个进程必须通过中间代理才能通信,创建新线程很简单,创建新进程需要对其父进程进行一次克隆

一个线程可以控制和操作统一进程里的其他线程,进程只能操作子进程

GIL:Global Interpreter Lock


直接调用

import threading
import time

def run(n):
    print("task:", n)
    time.sleep(2)

t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t3 = threading.Thread(target=run, args=("t3",))

t1.start()
t2.start()
t3.start()

"""
task: t1
task: t2
task: t3
"""

继承式调用


import threading
import time

class MyThread(threading.Thread):
    def __init__(self, n, sleep_time):
        super(MyThread, self).__init__()
        self.n = n
        self.sleep_time = sleep_time

    def run(self):  # 需要运行的代码
        print("task:", self.n)
        time.sleep(self.sleep_time)
        print("task done", self.n, threading.current_thread(), threading.active_count())

t1 = MyThread("t1", 2)
t2 = MyThread("t2", 3)
t3 = MyThread("t3", 4)

t1.start()
t2.start()
t3.start()

# 等待线程执行完毕继续主线程,阻塞
t1.join()  # wait()
t2.join()
t3.join()

print("...main...", threading.current_thread(), threading.active_count())  # 主线程

"""
task: t1
task: t2
task: t3
task done t1 <MyThread(Thread-1, started 7112)> 4
task done t2 <MyThread(Thread-2, started 5448)> 3
task done t3 <MyThread(Thread-3, started 4552)> 2
...main... <_MainThread(MainThread, started 2948)> 1
"""

多线程调用


# 主线程与子线程是并行的

import threading
import time

def run(n):
    print("task:", n)
    time.sleep(2)
    print("task done", n)

start_time = time.time()

threads = []  # 保存线程列表

for i in range(5):
    t = threading.Thread(target=run, args=("t%s"%i,))
    t.start()
    threads.append(t)

# 将所有线程阻塞
for t in threads:
    t.join()

end_time = time.time()
print("time:", end_time - start_time)
"""
task: t0
task: t1
task: t2
task: t3
task: t4
task done t4
task done t2
task done t3
task done t1
task done t0
time: 2.0103650093078613
"""

守护线程


import threading
import time

def run(n):
    print("task:", n)
    time.sleep(2)
    print("task done", n)

start_time = time.time()

threads = []  # 保存线程列表

for i in range(5):
    t = threading.Thread(target=run, args=("t%s"%i,))
    t.setDaemon(True)  # 设置为守护线程,主线程停止随之停止
    t.start()
    threads.append(t)

time.sleep(2)  # 等待部分线程执行完毕

end_time = time.time()
print("time:", end_time - start_time)
"""
task: t0
task: t1
task: t2
task: t3
task: t4
task done t2
task done t4
task done t3
task done t1
task done t0
time: 2.0087130069732666
"""

互斥锁


import threading
import time

num = 0
lock = threading.Lock()  # 实例化互斥锁

def run(n):
    global num
    lock.acquire()  # 申请锁
    time.sleep(2)
    num += 1
    lock.release()  # 释放锁
    print(num)

start_time = time.time()

threads = []  # 保存线程列表

for i in range(5):
    t = threading.Thread(target=run, args=("t%s"%i,))
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()  # 等待部分线程执行完毕

end_time = time.time()
print("time:", end_time - start_time)
print("num:", num)

"""
1
2
3
4
5
time: 10.027688980102539
num: 5
"""

递归锁


import threading
import time

num = 0
lock = threading.RLock()  # 实例化递归锁,此处用普通互斥锁会卡死

def run1():
    print("run1_start")
    lock.acquire() # 第二级锁
    print("run1")
    lock.release()

def run2():
    lock.acquire()  # 第二级锁
    print("run2")
    lock.release()

def run():
    lock.acquire()  # 第一级锁
    print("run1_begin")
    run1()
    print("run2_begin")
    run2()
    print("run_end")
    lock.release()  # 释放锁

start_time = time.time()

t = threading.Thread(target=run)
t.start()

# t.join()  # 等待全部线程执行完毕
while threading.active_count() > 1:
    print(threading.current_thread())

end_time = time.time()
print("time:", end_time - start_time)

"""
run1_begin
<_MainThread(MainThread, started 22552)>
<_MainThread(MainThread, started 22552)>
<_MainThread(MainThread, started 22552)>
run1_start
<_MainThread(MainThread, started 22552)>
run1
run2_begin
run2
run_end
time: 0.0
"""

信号锁


import threading
import time


semaphore = threading.BoundedSemaphore(5)  # 设置信号量,最多允许5个线程同时运行

def run(n):
    semaphore.acquire()  # 信号锁
    time.sleep(1)
    print("run", n)
    semaphore.release()

start_time = time.time()

for i in range(10):
    t = threading.Thread(target=run, args=(i,))
    t.start()

# 等待全部线程执行完毕
while threading.active_count() != 1:
    pass

end_time = time.time()
print("time:", end_time - start_time)

"""
run 1
run 2
run 4
run 0
run 3
run 5
run 7
run 8
run 9
run 6
time: 2.061771869659424
"""


上一篇:控制器如何获取一条url中存在多个Id


下一篇:centos7安装mysql5.7压缩包式安装