可以在内存中移动pthread_mutex_t吗? [英] Can a pthread_mutex_t be moved in memory?

查看:220
本文介绍了可以在内存中移动pthread_mutex_t吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个动态的pthread_mutex分配数组,该数组将随着时间的推移而增长(添加更多互斥锁).我的问题是,如果使用realloc()移动数组,它们是否仍将起作用.我担心的是pthread_mutex_init()可能会以某种方式设置依赖于互斥量地址的内部信息.

I would like to build a dynamic malloced array of pthread_mutex that will grow over time (adding more mutexes). My question is whether they will still work if the array gets moved with realloc(). My concern is that pthread_mutex_init() might somehow set up internal information that depends on the address of the mutex at that moment.

更具体地说,这是一个显示该问题的玩具片段:

To be more specific, here is a toy snippet that shows the issue:

pthread_mutex_t *my_mutexes = (pthread_mutex_t *) malloc (sizeof(pthread_mutex_t));
pthread_mutex_init (my_mutexes, NULL);
my_mutexes = (pthread_mutex_t *) realloc (my_mutexes, 2*sizeof(pthread_mutex_t));
/* does my_mutexes[0] still work at this point? */

我认为在所有此类情况下的答案都是如果没有明确允许,那就假设",但我想在这里获得圣人的建议.如果结论不是要这样做,那么我想知道,一般而言,我如何才能创建越来越多的互斥体列表.

I suppose the answer in all such cases is "if it's not expressly allowed, assume not" but I wanted to get the sage advice here. If the conclusion is not to do this, then I wonder how, in general, I might create a growing list of mutexes.

推荐答案

移动互斥锁并不安全.例如,Linux上的某些互斥锁实现使用futex系统调用,该调用专门等待互斥锁的地址.

It's not safe to move mutexes. Some mutex implementations on Linux, for example, use the futex system call which specifically waits on the address of the mutex.

如果需要动态增长,我建议使用pthread_mutex_t指针的主数组和该主列表的互斥体.当增加数组时,您将仅移动指针列表,而不是互斥体本身.互斥锁可以用普通的malloc分配.

If it needs to grow dynamically, I'd suggest using a master array of pthread_mutex_t pointers and a mutex for that master list. When you grow the array, you will just be moving the list of pointers rather than the mutexes themselves. The mutexes can be allocated with plain malloc.

这篇关于可以在内存中移动pthread_mutex_t吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆