如何在 Python 2.6 中获得线程安全打印?
- 2025-03-20 08:46:00
- admin 原创
- 36
问题描述:
print
根据这些 文章, Python 中的不是线程安全的。
后一篇文章中提供了 Python 3 的解决方法。
如何print
在 Python 2.6 中实现线程安全?
解决方案 1:
有趣的问题 - 考虑到语句中发生的所有事情print
,包括属性的设置和检查softspace
,使其成为“线程安全的”(实际上意味着:打印的线程仅在打印换行符时将“标准输出的控制权”交给另一个线程,以便保证输出的每一整行都来自单个线程)是一个有点挑战(通常简单的实际线程安全方法 - 委托一个单独的线程来专门“拥有”和处理sys.stdout
,通过 Queue.Queue 与其通信 - 并不是那么有用,因为问题不是线程安全[[即使使用普通的print
也没有崩溃的风险,并且最终出现在标准输出上的字符正是那些被打印的字符]]而是需要在线程之间互斥以实现扩展的操作范围)。
所以,我认为我成功了...:
import random
import sys
import thread
import threading
import time
def wait():
time.sleep(random.random())
return 'W'
def targ():
for n in range(8):
wait()
print 'Thr', wait(), thread.get_ident(), wait(), 'at', wait(), n
tls = threading.local()
class ThreadSafeFile(object):
def __init__(self, f):
self.f = f
self.lock = threading.RLock()
self.nesting = 0
def _getlock(self):
self.lock.acquire()
self.nesting += 1
def _droplock(self):
nesting = self.nesting
self.nesting = 0
for i in range(nesting):
self.lock.release()
def __getattr__(self, name):
if name == 'softspace':
return tls.softspace
else:
raise AttributeError(name)
def __setattr__(self, name, value):
if name == 'softspace':
tls.softspace = value
else:
return object.__setattr__(self, name, value)
def write(self, data):
self._getlock()
self.f.write(data)
if data == '
':
self._droplock()
# comment the following statement out to get guaranteed chaos;-)
sys.stdout = ThreadSafeFile(sys.stdout)
thrs = []
for i in range(8):
thrs.append(threading.Thread(target=targ))
print 'Starting'
for t in thrs:
t.start()
for t in thrs:
t.join()
print 'Done'
调用的wait
目的是在没有这种互斥保证的情况下保证混乱混合的输出(注释由此而来)。 使用包装,即上面的代码与那里看起来完全一样,并且(至少)Python 2.5 及更高版本(我相信这也可以运行在早期版本中,但我手头没有任何可以方便检查的版本)输出为:
Thr W -1340583936 W at W 0
Thr W -1340051456 W at W 0
Thr W -1338986496 W at W 0
Thr W -1341116416 W at W 0
Thr W -1337921536 W at W 0
Thr W -1341648896 W at W 0
Thr W -1338454016 W at W 0
Thr W -1339518976 W at W 0
Thr W -1340583936 W at W 1
Thr W -1340051456 W at W 1
Thr W -1338986496 W at W 1
...more of the same...
“序列化”效果(线程似乎像上面一样“很好地循环”)是这样一个事实的副作用:成为当前打印线程的线程比其他线程慢得多(所有这些等待!-)。注释掉 in time.sleep
,wait
输出改为
Thr W -1341648896 W at W 0
Thr W -1341116416 W at W 0
Thr W -1341648896 W at W 1
Thr W -1340583936 W at W 0
Thr W -1340051456 W at W 0
Thr W -1341116416 W at W 1
Thr W -1341116416 W at W 2
Thr W -1338986496 W at W 0
...more of the same...
即更典型的“多线程输出”......除了保证输出中的每一行都完全来自一个线程。
当然,例如,执行此操作的线程print 'ciao',
将保留标准输出的“所有权”,直到它最终执行不带尾随逗号的打印,而想要打印的其他线程可能会休眠一段时间(否则如何保证输出中的每一行都来自单个线程?好吧,一种架构是将部分行累积到线程本地存储中,而不是实际将它们写入标准输出,并且仅在收到`...时才进行写入,我担心这很难与
softspace`设置正确交织,但可能是可行的)。
解决方案 2:
通过实验,我发现下面的方法有效、简单并且适合我的需求:
print "your string here
",
或者,将其包装到一个函数中,
def safe_print(content):
print "{0}
".format(content),
我的理解是,正常的隐式换行符print
实际上是在单独的操作中输出到 stdout 的,从而导致与其他print
操作的竞争条件。通过用添加的,
, 删除此隐式换行符,而是将换行符包含在字符串中,我们可以避免此问题。
2020 年编辑:这是 Python 3 版本(感谢评论中的 Bob Stein 给予的启发):
def safe_print(*args, sep=" ", end="", **kwargs):
joined_string = sep.join([ str(arg) for arg in args ])
print(joined_string + "
", sep=sep, end=end, **kwargs)
正如 Bob Stein 所指出的,依靠print
连接多个传递的参数会导致输出混乱,所以我们必须自己做。
2017 年编辑:这个答案开始引起一些关注,所以我只是想澄清一下。这实际上并不完全是“线程安全的”。如果s 相隔微秒,print
则输出的顺序可能不正确。然而,这样做可以避免从并发线程执行的语句产生乱码输出,而这正是大多数人在问这个问题时真正想要的。print
`print`
以下测试可以说明我的意思:
from concurrent.futures import ThreadPoolExecutor
def normal_print(content):
print content
def safe_print(content):
print "{0}
".format(content),
with ThreadPoolExecutor(max_workers=10) as executor:
print "Normal Print:"
for i in range(10):
executor.submit(normal_print, i)
print "---"
with ThreadPoolExecutor(max_workers=10) as executor:
print "Safe Print:"
for i in range(10):
executor.submit(safe_print, i)
输出:
Normal Print:
0
1
23
4
65
7
9
8
----
Safe Print:
1
0
3
2
4
5
6
7
8
9
解决方案 3:
问题是 Python 使用单独的操作码来打印 NEWLINE 和打印对象本身。最简单的解决方案可能是仅使用带有显式换行符的显式 sys.stdout.write。
解决方案 4:
我不知道是否有更好的方法可以替代这种锁定机制,但至少看起来很容易。我也不确定打印是否真的不是线程安全的。
编辑:好的,现在我自己测试了一下,你是对的,你可以得到看起来非常奇怪的输出。而且你不需要未来的导入,它就在那里,因为我使用的是 Python 2.7。
from __future__ import print_function
from threading import Lock
print_lock = Lock()
def save_print(*args, **kwargs):
with print_lock:
print (*args, **kwargs)
save_print("test", "omg", sep='lol')
扫码咨询,免费领取项目管理大礼包!