并发访问和自由堆对象 [英] concurrent access and free of heap object

查看:249
本文介绍了并发访问和自由堆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题是一个可能的子问题,这个<一个href=\"http://stackoverflow.com/questions/9115876/concurrent-access-and-free-of-a-data-structure\">concurrent数据结构的连接和免费

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;
};

我需要一个解决方案,确定通过,我可以同时访问类型DS和自由吧1对象。

I need a deterministic solution via which I can concurrently access 1 object of type ds and free it.

约束:


  1. 您可以互斥的指针,但不能把它拿出来的对象。

真正的问题:

免费不能做持有锁,因为,再由锁占用的内存也会丢失。

Free can't be done holding the lock because, then memory occupied by the lock is also lost.

我看了很多关于裁判计数的论文和文章,但他们每个人保持DS外面的锁。我想一个解决方案,我可以保持一个锁或参考DS里面的锁。

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.

推荐答案

既然你说的互斥体可以是一个指针,你可以做这样的事情:

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);
}

在我看来,虽然,销毁的对象是不是真的东西,适合并发访问/同步成语。如果你摧毁的东西,它不再出现,让所有的线程都受此影响。一个线程应该是怎样知道一个给定的 DS 指针是否仍然指向的东西是否有效?

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?

相反,你应该有一个的集合的DS 某处对象,并插入/删除访问该集合应有自己的,独立,收藏范围互斥。每当一个线程想要获得集合中的对象的引用,它应该这样做下一个互斥体的后卫,以及收集应该知道谁是目前持有的引用。

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.

这篇关于并发访问和自由堆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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