Explore / Programming python中如何获取等待某一个互斥锁的线程数量 Save Share Download ▾ Report Assistant2023-04-30 00:48 UTC Copy response
在Python中,如果需要获取等待某个互斥锁(如threading.Lock或threading.Semaphore)的线程数量,可以创建一个自定义的锁系统,以记录被锁住了的线程数量。以下是一个自定义锁类的实现示例:
Assistant2023-04-30 00:55 UTC Copy response
为了使自定义锁类成为线程安全的,我们需要为内部等待线程计数器添加额外的锁,以确保并发线程能正确更新和读取这个计数器。下面是一种改进的实现(已更新为线程安全):
Assistant2023-04-30 01:06 UTC Copy response
要使自定义锁类能够使用 with 语句,你需要在 CustomLock 类中实现关键的 __enter__() 和 __exit__() 方法。__enter__() 方法用于在 with 语句的开始时获取锁,而 __exit__() 方法用于在其结束时释放锁。这里是实现的示例:
Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 3 (6 messages)
Language zh
Conversation date Apr 30, 2023
Added to archive Nov 16, 2026
ID 01m7h4190wskn8qcpbqv1reyvkSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 948dc387167882b4fb05f46808f2c7c0
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
import threading
class CustomLock:
def __init__(self):
self.lock = threading.Lock()
self.waiting_threads = 0
def acquire(self, blocking=True, timeout=-1):
if blocking and timeout == -1:
self.waiting_threads += 1
acquired = self.lock.acquire()
if acquired:
self.waiting_threads -= 1
return acquired
elif blocking and timeout != -1:
self.waiting_threads += 1
acquired = self.lock.acquire(timeout=timeout)
if acquired:
self.waiting_threads -= 1
return acquired
else:
acquired = self.lock.acquire(blocking)
return acquired
def release(self):
self.lock.release()
def get_waiting_threads(self):
return self.waiting_threads
这个定制的锁类添加了一个名为waiting_threads的成员变量,该变量会在调用acquire()时增加,在成功获取锁后减少。新增加的get_waiting_threads方法可以用于获取等待的线程数量。
以下是一个简单的示例,展示了如何使用这个自定义锁类:
python Copy code
import time
def worker(custom_lock):
custom_lock.acquire()
print('Acquired the lock. Total waiting threads:', custom_lock.get_waiting_threads())
time.sleep(1)
custom_lock.release()
print('Released the lock.')
if __name__ == '__main__':
custom_lock = CustomLock()
threads = []
for _ in range(5):
thread = threading.Thread(target=worker, args=(custom_lock,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
请注意,这个实现可能不是线程安全的 – 将锁的状态与锁的逻辑混在一起可能导致一些问题,尤其是在高度竞争的情况下。
import threading
class CustomLock:
def __init__(self):
self.lock = threading.Lock()
self.waiting_threads = 0
self.waiting_threads_lock = threading.Lock() # 新增用于保护计数器的锁
def acquire(self, blocking=True, timeout=-1):
with self.waiting_threads_lock: # 在修改计数器前先加锁
if blocking and timeout == -1:
self.waiting_threads += 1
acquired = self.lock.acquire()
if acquired:
self.waiting_threads -= 1
return acquired
elif blocking and timeout != -1:
self.waiting_threads += 1
acquired = self.lock.acquire(timeout=timeout)
if acquired:
self.waiting_threads -= 1
return acquired
else:
acquired = self.lock.acquire(blocking)
return acquired
def release(self):
self.lock.release()
def get_waiting_threads(self):
with self.waiting_threads_lock: # 在读取计数器前先加锁
return self.waiting_threads
在这个改进的实现中,我们添加了一个新的成员变量(waiting_threads_lock),它是一个用于保护我们的等待线程计数器的额外锁。此外,在更新和获取等待线程计数器之前,我们使用with语句来确保锁住这个锁。这样我们就确保了在任何时候同时只有一个线程可以访问和修改等待线程计数器,从而实现了线程安全。
import threading
class CustomLock:
def __init__(self):
self.lock = threading.Lock()
self.waiting_threads = 0
self.waiting_threads_lock = threading.Lock()
def acquire(self, blocking=True, timeout=-1):
with self.waiting_threads_lock:
if blocking and timeout == -1:
self.waiting_threads += 1
acquired = self.lock.acquire()
if acquired:
self.waiting_threads -= 1
return acquired
elif blocking and timeout != -1:
self.waiting_threads += 1
acquired = self.lock.acquire(timeout=timeout)
if acquired:
self.waiting_threads -= 1
return acquired
else:
acquired = self.lock.acquire(blocking)
return acquired
def release(self):
self.lock.release()
def get_waiting_threads(self):
with self.waiting_threads_lock:
return self.waiting_threads
def __enter__(self): # 实现 `__enter__()` 方法,用于在 `with` 语句的开始获取锁
self.acquire()
return self
def __exit__(self, exc_type, exc_val, exc_tb): # 实现 `__exit__()` 方法,用于在 `with` 语句的结束释放锁
self.release()
现在你可以在 with 语句中使用 CustomLock 类的实例了。这里是如何使用它的示例:
python Copy code
import time
def worker(custom_lock):
with custom_lock: # 使用 `with` 语句来自动获取和释放锁
print('Acquired the lock. Total waiting threads:', custom_lock.get_waiting_threads())
time.sleep(1)
print('Released the lock.')
if __name__ == '__main__':
custom_lock = CustomLock()
threads = []
for _ in range(5):
thread = threading.Thread(target=worker, args=(custom_lock,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
with 语句会在进入其代码块时自动调用 __enter__() 方法,并在退出时调用 __exit__() 方法。这使得代码更简洁,避免了不必要的手动调用 acquire() 和 release() 方法。
Not yet included in a published release.