在共享内存中初始化pthread互斥锁 [英] Initializing a pthread mutex in shared memory
问题描述
我可以使用初始化程序在静态内存中初始化互斥锁:
I can initialize a mutex in static memory with an initializer:
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
但是如何在共享内存中初始化一个呢?在共享内存中,我必须与初始化变量分开来分配内存?我可以做memcpy()吗?
but how do I initialize one in shared memory where I have to allocate the memory separately from initializing the variable? Can I do a memcpy()?
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
memcpy(&globalmutex, &mymutex, sizeof(mymutex);
我以为我记得很久以前读过,当将一个互斥量分配到保证要初始化为零的内存中时,它不需要初始化-恰恰是在这种情况下-但我找不到写下来的内容任何地方.那是真的吗?-我注意到PTHREAD_MUTEX_INITIALIZER在我的redhat系统上定义为{{0,0,0,0,0,0,{0,0}}}.
I thought I remembered reading a long time ago that when allocating a mutex into memory guaranteed to be initialized to zero's, it doesn't need initialization--intended for exactly this case--but I can't find that written down anywhere. Is that really true?--I notice that PTHREAD_MUTEX_INITIALIZER is defined as { { 0, 0, 0, 0, 0, 0, { 0, 0 } } } on my redhat system.
推荐答案
在这里您需要小心,并非所有实现都支持可以在各个进程中工作的互斥体.
You need to be careful here, not all implementations support mutexes that can work across processes.
PThreads本身通过使用进程共享属性来支持此功能,但是,如果需要的话,将不会使用默认的初始化程序.
PThreads itself supports this by use of the process shared attribute but, if you want that, you won't be using the default initialiser.
相反,在正确构造互斥量属性结构之后,您将需要使用pthread_mutex_init()
:
Instead you'll need to use pthread_mutex_init()
after properly constructing a mutex attribute structure:
int pthread_mutex_init(
pthread_mutex_t *mutex,
const pthread_mutexattr_t *attr);
最好的选择是只在共享内存中分配空间,然后将其强制转换为正确的类型,然后将其传递给init
函数.我认为这可能比初始化后将其复制更为安全.
Best bet would be to just allocate space in shared memory then cast it to the correct type and pass it to the init
function. I think that may be safer than copying it after the initialisation.
这篇关于在共享内存中初始化pthread互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!