Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
template<typename container="">
class Lock {
public:
    // have been omitted
    Lock(const Container& container)
        : c(container){
            getMutexFor(c);
    }
 
    ~Lock() {
        releaseMutexFor(c);
    }
private:
    const Container& c;
};


How to realize the releaseMutexFor and getMutexFor?
Posted
Updated 20-Nov-13 7:54am
v2
Comments
Philippe Mori 20-Nov-13 18:33pm    
Contrary to .NET (C#, C++/CLI...), I don't think it is possible to do that in C++. One of the way would be to have a structure that contains the container and its lock... or maybe have a wrapped class so that no direct access is made to the container.

Your idea is intriguing, but I guess it won't work. For a mutex to be effective it has to be part of or at least associated to the object it is supposed to protect. So you don't want to have one mutex per Lock object, but one mutex per container object.

A possible mechanism would be to allocate a map in you lock class that associates each container object with a dedicated mutex that is help by the Lock object. However, this approach won't really work, because your Lock object will not be informed when a container is destroyed. And hence your map will get bigger and bigger over time.

I don't see how it could be effectively done what you are trying.
 
Share this answer
 
Comments
Philippe Mori 20-Nov-13 18:29pm    
And I guess you would have to lock access to the map... so in the end it won't be much better than using a single lock...
nv3 21-Nov-13 2:13am    
Yes, that's true, it would even be much slower than planting the mutex in the object that is to be shared.
Why don't you use C++11 locks? See, for instance C++11 threads, locks and condition variables[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900