
线程(英语: thread)是操作系统可以执行操作调度的最小单元.
并发性: 当任务数大于CPU内核数时,将通过内核调度“一起”执行多个任务.
并行: 这意味着任务数小于或等于CPU内核数多线程避免死锁多线程避免死锁,也就是说,这些任务实际上是一起执行的.

同步: 它是协调同步,按预定顺序运行.
互锁: 解决线程之间资源竞争不安全的问题.
死锁: 多个线程获取多个锁,导致A需要由B持有的锁,而B需要由A持有的锁.

防止死锁: 尝试在程序设计期间避免死锁,添加超时并为程序中的每个锁分配唯一的ID.
同步源语言:
当进程调用发送原语时,在开始发送消息之后,发送进程处于阻塞状态. 消息完全发送之后,send原语的后续语句可以继续执行. 当进程调用接收原语时,它不会立即返回控制,而是等待直到消息被实际接收并将其放入指定的接收区域,然后再返回控制并继续执行原语的后续指令. 在此期间,它已被阻止. 上面的发送和接收称为同步通信原语或阻塞通信原语.

在python多线程之间共享数据
# Code to execute in an independent thread
import time
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5)
# Create and launch a thread
from threading import Thread
t = Thread(target=countdown, args=(10,))
t.start()
默认情况下,主线程将在执行后等待子线程执行.

from queue import Queue
from threading import Thread
# A thread that produces data
def producer(out_q):
while True:
# Produce some data
...
out_q.put(data)
# A thread that consumes data
def consumer(in_q):
while True:
# Get some data
data = in_q.get()
# Process the data
...
# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()
队列对象已经包含必需的锁.
import threading
class SharedCounter:
'''
A counter object that can be shared by multiple threads.
'''
def __init__(self, initial_value = 0):
self._value = initial_value
self._value_lock = threading.Lock()
def incr(self,delta=1):
'''
Increment the counter with locking
'''
with self._value_lock:
self._value += delta
def decr(self,delta=1):
'''
Decrement the counter with locking
'''
with self._value_lock:
self._value -= delta
使用threading.Lock()获得互斥锁.
# 创建锁
mutex = threading.Lock()
# 锁定
mutex.acquire()
# 释放
mutex.release()
指定获取锁的顺序,例如id(lock)从最小到最大排序.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-233508-1.html
噗
泻作屎
侵犯中国主权