vendredi 28 août 2015

How to maintain a thread safe reference to an element in another class

I have a class (class A) that is using the monitor pattern for safe access to a std::deque. Any time I need to simply add or remove an element I am fine. But sometimes a different class (Class B) needs to call in and get a reference to an element in the deque in Class A. I have been returning an iterator to that element, but there's the chance that another thread could 'push' a new element into Class A and invalidate the iterator that the Class B is using. The only way I can think to prevent this is to lock a mutex in Class A before returning the iterator, and then have the Class B call another function when it's finished to release the mutex, but this seems hackey. Any Ideas for a cleaner way.

Thanks.

Aucun commentaire:

Enregistrer un commentaire