3

I am allocating memory using mmap to store some data in set associative manner where I want to access sets concurrently. So, if there are K sets then I am allocating K+1 slots per set where first slot is used for metadata. Here at start of metadata slot I want to store a lock. So how do I create a lock at this specific location? I found using sizeof operator that size of lock is 40B. So I made sure each entry is atleast 40B.

Normally, we create pthread lock using

pthread_mutex_t lock;

So, is it safe to just copy 40B of lock variable to required location?

As it is difficult to debug concurrent program it will be great if someone can tell if it is right way to do it. Thank you.

1 Answers1

5

Copying POSIX synchronization objects is never safe. In order to turn a memory location into a mutex, you can use 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.

On GNU/Linux, you must link all participating processes with -lpthread (or build with -pthread), otherwise the program will run, but use the optimized mutex implementation in libc instead of libpthread, which does not have support for process-shared mutexes.

user3386109
  • 34,287
  • 7
  • 49
  • 68
Florian Weimer
  • 32,022
  • 3
  • 48
  • 92