问题
This question is a possible sub problem to this concurrent access and free of a data structure
The other question is open to design, this one is more concrete.
struct ds
{
int x,y,z;
pthread_mutex_t mutex;
};
I need a deterministic solution via which I can concurrently access 1 object of type ds and free it.
Constrains:
- You can make mutex a pointer but can't take it out of the object.
The real problem:
Free can't be done holding the lock because, then memory occupied by the lock is also lost.
I have read lot of papers and articles on ref counting, but each one of them keeps a lock outside the ds. I want a solution where I can keep a lock or reference to the lock inside the ds.
回答1:
Since you say that "mutex can be a pointer", you could do something like this:
struct ds { pthread_mutex_t * mutex; /* ... */ };
struct ds * create_ds()
{
struct ds * p = calloc(1, sizeof(struct ds));
pthread_mutex_t * q = malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(q, NULL);
ds->mutex = q;
return p;
}
void free_ds(struct ds * p)
{
pthread_mutex_t * q = p->mutex;
pthread_mutex_lock(q);
free(p);
pthread_mutex_unlock(q);
pthread_mutex_destroy(q);
free(q);
}
In my opinion, though, destroying an object is not really something that fits the concurrent-access/synchronization idiom. If you destroy something, it's no longer there, so all threads are affected by this. How is a thread supposed to know whether a given ds
pointer still points to something valid?
Instead, you should probably have a collection of ds
objects somewhere, and insert/erase access to that collection should have its own, separate, collection-wide mutex. Everytime a thread wants to obtain a reference to an object in the collection, it should do so under guard of a mutex, and the collection should know who is currently holding references.
来源:https://stackoverflow.com/questions/9117007/concurrent-access-and-free-of-heap-object