python 并行编程 多线程 锁 信号 条件 事件

共享内存

class threading.Thread(group=None,
target=None,
name=None,
args=(),
kwargs={})
import threading

def function(i):
print ("function called by thread %i\n" % i)
return

threads = []

for i in range(5):
t = threading.Thread(target=function , args=(i, ))
threads.append(t)
t.start()
t.join()

2、线程继承
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
def init(self, threadID, name, counter):
threading.Thread.init(self)
self.threadID = threadID
self.name = name
self.counter = counter

def run(self):
    print("Starting " + self.name)
    print_time(self.name, self.counter, 5)
    print("Exiting " + self.name)

def print_time(threadName, delay, counter):
while counter:
if exitFlag:
# 译者注:原书中使用的thread,但是Python3中已经不能使用thread,以_thread取代,因此应该
# import _thread
# _thread.exit()
thread.exit()
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1

Create new threads

thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

Start new Threads

thread1.start()
thread2.start()

以下两行为译者添加,如果要获得和图片相同的结果,

下面两行是必须的。疑似原作者的疏漏

thread1.join()
thread2.join()
print("Exiting Main Thread")

3、threading.Lock() l.acquire() l.release()

-- coding: utf-8 --

import threading

shared_resource_with_lock = 0
shared_resource_with_no_lock = 0
COUNT = 100000
shared_resource_lock = threading.Lock()

有锁的情况

def increment_with_lock():
global shared_resource_with_lock
for i in range(COUNT):
shared_resource_lock.acquire()
shared_resource_with_lock += 1
shared_resource_lock.release()

def decrement_with_lock():
global shared_resource_with_lock
for i in range(COUNT):
shared_resource_lock.acquire()
shared_resource_with_lock -= 1
shared_resource_lock.release()

没有锁的情况

def increment_without_lock():
global shared_resource_with_no_lock
for i in range(COUNT):
shared_resource_with_no_lock += 1

def decrement_without_lock():
global shared_resource_with_no_lock
for i in range(COUNT):
shared_resource_with_no_lock -= 1

if name == "main":
t1 = threading.Thread(target=increment_with_lock)
t2 = threading.Thread(target=decrement_with_lock)
t3 = threading.Thread(target=increment_without_lock)
t4 = threading.Thread(target=decrement_without_lock)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print ("the value of shared variable with lock management is %s" % shared_resource_with_lock)
print ("the value of shared variable with race condition is %s" % shared_resource_with_no_lock)

///rlock()
4| threading.Semaphore(0)

-- coding: utf-8 --

"""Using a Semaphore to synchronize threads"""
import threading
import time
import random

The optional argument gives the initial value for the internal

counter;

it defaults to 1.

If the value given is less than 0, ValueError is raised.

semaphore = threading.Semaphore(0)

def consumer():
print("consumer is waiting.")
# Acquire a semaphore
semaphore.acquire()
# The consumer have access to the shared resource
print("Consumer notify : consumed item number %s " % item)

def producer():
global item
time.sleep(10)
# create a random item
item = random.randint(0, 1000)
print("producer notify : produced item number %s" % item)
# Release a semaphore, incrementing the internal counter by one.
# When it is zero on entry and another thread is waiting for it
# to become larger than zero again, wake up that thread.
semaphore.release()

if name == 'main':
for i in range (0,5) :
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
t1.join()
t2.join()
print("program terminated")

5\ condition() 生产者,消费者
from threading import Thread, Condition
import time

items = []
condition = Condition()

class consumer(Thread):

def __init__(self):
    Thread.__init__(self)

def consume(self):
    global condition
    global items
    condition.acquire()
    if len(items) == 0:
        condition.wait()
        print("Consumer notify : no item to consume")
    items.pop()
    print("Consumer notify : consumed 1 item")
    print("Consumer notify : items to consume are " + str(len(items)))

    condition.notify()
    condition.release()

def run(self):
    for i in range(0, 20):
        time.sleep(2)
        self.consume()

class producer(Thread):

def __init__(self):
    Thread.__init__(self)

def produce(self):
    global condition
    global items
    condition.acquire()
    if len(items) == 10:
        condition.wait()
        print("Producer notify : items producted are " + str(len(items)))
        print("Producer notify : stop the production!!")
    items.append(1)
    print("Producer notify : total items producted " + str(len(items)))
    condition.notify()
    condition.release()

def run(self):
    for i in range(0, 20):
        time.sleep(1)
        self.produce()

if name == "main":
producer = producer()
consumer = consumer()
producer.start()
consumer.start()
producer.join()
consumer.join()

(译者在这里添加一段。乍一看这段代码好像会死锁,因为 condition.acquire() 之后就在 .wait() 了,好像会一直持有锁。其实 .wait() 会将锁释放,然后等待其他线程 .notify() 之后会重新尝试获得锁。但是要注意 .notify() 并不会自动释放锁,所以代码中有两行,先 .notify() 然后再 .release() 。

6、event事件使用

-- coding: utf-8 --

import time
from threading import Thread, Event
import random
items = []
event = Event()

class consumer(Thread):
def init(self, items, event):
Thread.init(self)
self.items = items
self.event = event

def run(self):
    while True:
        time.sleep(2)
        self.event.wait()
        item = self.items.pop()
        print('Consumer notify : %d popped from list by %s' % (item, self.name))

class producer(Thread):
def init(self, integers, event):
Thread.init(self)
self.items = items
self.event = event

def run(self):
    global item
    for i in range(1):
        time.sleep(2)
        item = random.randint(0, 256)
        self.items.append(item)
        print('Producer notify : item N° %d appended to list by %s' % (item, self.name))
        print('Producer notify : event set by %s' % self.name)
        self.event.set()
        print('Produce notify : event cleared by %s '% self.name)
        self.event.clear()

if name == 'main':
t1 = producer(items, event)
t2 = consumer(items, event)
t1.start()
t2.start()
t1.join()
t2.join()

7、with
import threading
import logging
logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s',)

def threading_with(statement):
with statement:
logging.debug('%s acquired via with' % statement)

def threading_not_with(statement):
statement.acquire()
try:
logging.debug('%s acquired directly' % statement )
finally:
statement.release()

if name == 'main':
# let's create a test battery
lock = threading.Lock()
rlock = threading.RLock()
condition = threading.Condition()
mutex = threading.Semaphore(1)
threading_synchronization_list = [lock, rlock, condition, mutex]
# in the for cycle we call the threading_with e threading_no_with function
for statement in threading_synchronization_list :
t1 = threading.Thread(target=threading_with, args=(statement,))
t2 = threading.Thread(target=threading_not_with, args=(statement,))
t1.start()
t2.start()
t1.join()
t2.join()

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容

  • 线程 操作系统线程理论 线程概念的引入背景 进程 之前我们已经了解了操作系统中进程的概念,程序并不能单独运行,只有...
    go以恒阅读 1,630评论 0 6
  • 环境 xubuntu anaconda pycharm python https://www.cnblogs.co...
    Ericoool阅读 1,891评论 0 0
  • 线程 1.同步概念 1.多线程开发可能遇到的问题 同步不是一起的意思,是协同步调 假设两个线程t1和t2都要对nu...
    TENG书阅读 602评论 0 1
  • 一文读懂Python多线程 1、线程和进程 计算机的核心是CPU,它承担了所有的计算任务。它就像一座工厂,时刻在运...
    星丶雲阅读 1,443评论 0 4
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 2,730评论 0 8