Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
volatile thread-safe object
//Title of this code #include <iostream> #include <mutex> using namespace std; class ThreadSafeObject { private: std::mutex mutex_; public: virtual ~ThreadSafeObject() { } void Lock() { std::cout<<"Locking...\n"; mutex_.lock(); } void Unlock() { std::cout<<"Unlocking...\n"; mutex_.unlock(); } }; template<typename T> class LockedPtr { private: ThreadSafeObject &p_; public: LockedPtr(volatile ThreadSafeObject &p) : p_(const_cast<ThreadSafeObject&>(p)) { p_.Lock(); } ~LockedPtr() { p_.Unlock(); } public: T * operator->() { return dynamic_cast<T*>(&p_); }; }; class SharedObj : public ThreadSafeObject { public: SharedObj() { } void method1() volatile { std::cout<<"method 1 called (thread-safe)!\n"; } void method2() { std::cout<<"method 2 called (critical section only)!\n"; } }; template<typename T> LockedPtr<T> get_locked(volatile T &_p) { return LockedPtr<T>(_p); } int main() { volatile SharedObj obj; obj.method1(); { auto ptr = get_locked(obj); ptr->method2(); } obj.method1(); }
run
|
edit
|
history
|
help
0
compile-time check of existness of method of a class
Reverese every K node in list
srednie
simple serialization
Przesylka
Ineritance
2
same
NonparaU
Test 20(2020)