文件名称:保存线程的状态信息-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:42
python cookbook 第3版 高清 中文完整版
12.6 保存线程的状态信息 问题 You need to store state that’s specific to the currently executing thread and not visible to other threads. 解决方案 Sometimes in multithreaded programs, you need to store data that is only specific to the currently executing thread. To do this, create a thread-local storage object using threading.local(). Attributes stored and read on this object are only visible to the executing thread and no others. As an interesting practical example of using thread-local storage, consider the LazyCon nection context-manager class that was first defined in Recipe 8.3. Here is a slightly modified version that safely works with multiple threads: from socket import socket, AF_INET, SOCK_STREAM import threading class LazyConnection: def __init__(self, address, family=AF_INET, type=SOCK_STREAM): self.address = address self.family = AF_INET self.type = SOCK_STREAM self.local = threading.local() def __enter__(self): if hasattr(self.local, ‘sock’): raise RuntimeError(‘Already connected’) self.local.sock = socket(self.family, self.type) self.local.sock.connect(self.address) return self.local.sock