解锁时向多个线程发出信号的一把锁

One lock that signals multiple threads when unlocked

有没有一种方法可以实现由两个组件使用的锁,当由多个线程组成的第一个组件等待一个锁定的锁,第二个组件收到锁并解锁它,这会向所有其他线程发出信号等等?

需要跨平台(C实现)

那么有没有办法设计这样的东西呢?

没有一种跨平台解决方案可以同时用于 POSIX 和 Windows 系统,假设这些是您的目标系统。

在 POSIX 系统上,使用条件变量并调用 pthread_cond_broadcast() 来解锁所有等待线程:

SYNOPSIS

#include <pthread.h>

int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);

DESCRIPTION

These functions shall unblock threads blocked on a condition variable.

The pthread_cond_broadcast() function shall unblock all threads currently blocked on the specified condition variable cond.

...

在 Windows,you can use WakeAllConditionVariable

Wake all threads waiting on the specified condition variable.

Syntax

C++

VOID WINAPI WakeAllConditionVariable(
  _Inout_ PCONDITION_VARIABLE ConditionVariable
);

编写自己的跨平台条件变量包装器并不难,它在 POSIX 系统上包装 POSIX 条件变量,在 Windows 系统上包装 Windows 条件变量.