如何使用 pthread 库在堆上的特定位置创建锁?

How to create lock at specific location on heap using pthread library?

我正在使用 mmap 分配内存以集合关联方式存储一些数据,我想在其中同时访问集合。因此,如果有 K 个集合,那么我将为每个集合分配 K+1 个槽位,其中第一个槽位用于元数据。在元数据插槽的开头,我想存储一个锁。那么如何在这个特定位置创建锁呢?我发现使用 sizeof 运算符,锁的大小是 40B。所以我确保每个条目至少为 40B。

通常,我们使用

创建pthread锁

pthread_mutex_t lock;

那么,将 40B 的锁变量复制到所需位置是否安全?

由于调试并发程序很困难,如果有人能判断它是否是正确的方法,那就太好了。谢谢。

复制POSIX 同步对象永远不安全。为了将内存位置变成互斥锁,您可以使用 pthread_mutex_init. If the mapping is process-shared, you need to create a process-shared mutex, using a mutex attribute which was set up using pthread_mutexattr_setpshared.

在 GNU/Linux 上,您必须 link 所有参与进程 -lpthread(或使用 -pthread 构建),否则程序将 运行,但是在 libc 中使用优化的互斥锁实现而不是 libpthread,后者不支持进程共享互斥锁。