473,406 Members | 2,390 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Making a class threadsafe / Locking a const accessor

12
Good day all,

Is there a logical way to lock data in an accessor?

Because accessors are generally declared as const methods and a lock() operation is not, how can you lock the class internally when the accessor is called?

For example:
Expand|Select|Wrap|Line Numbers
  1. class Class
  2. {
  3. public:
  4.   int GetValue() const;
  5.  
  6. protected:
  7.   void Lock();
  8.   void Unlock();
  9.  
  10. private:
  11.   int m_Value;
  12. }
  13.  
When I implement GetValue(), i'd like to do:
Expand|Select|Wrap|Line Numbers
  1. int Class::GetValue()
  2. {
  3.   Lock();
  4.   int TmpValue = m_Value;
  5.   Unlock();
  6.   return(TmpValue);
  7. }
  8.  
But obviously this isn't good, since Lock/Unlock aren't const (and can't be).

I am sure I am not the first to try to make a class thread safe so I guess I'm just missing something...

Thanks!


EDIT: Strangely, I knew of a possible solution and yet it just disappeared from my head: using const_cast on the instance of the class (or lock) would be a valid solution. But would it be the best? What do you think?
Jul 8 '08 #1
6 2936
Banfa
9,065 Expert Mod 8TB
OK this is a guess but you could try declaring lock and unlock mutable (this is a C++ keyword). I believe that would make them modifiable even in a situation that normally requires constness, such as an accessor.
Jul 9 '08 #2
Sirmont
12
This is just absolutely perfect! Exactly what I need! Thanks!
Jul 10 '08 #3
hdanw
61
May not be what you want.

Can you Identify what the scope is on this Lock() call?

Essentially a mutex m, is either locked, or unlocked.

The OS core, is not selective about who acquires the mutex, when.

So lets say that you are in a multi threaded environment, as is the case when synchronization is required, and you have a mutex, which is inherently associated with the object / instance.

So when you call Lock(), you are in essence calling ParentClass.Lock().

Which means that accessors for other data elements are waiting for exclusive access to that object instance before they can write.

If mutlple calls come in for seperate data members it wont matter. And since the OS is not selective, one accessor can be held indefinately while other accessors do there jobs. Potentially dogging your system. And takeing away any advantage you hoped to gain by being multi-Threaded.

A better way is to create a Critical Section for each Specific Data Item or member. So that calls to that accessor is only blocking other calls to that same accessor. and the Other Accessors can freely access their data simultaneously.

So, to speed up your application serialize the accessors for each data member, instead of serializing access to the intire object instance.


Expand|Select|Wrap|Line Numbers
  1. The steps are easy ...
  2.  
  3. 1. at instantiation call InitializeCriticalSection() for each data member.
  4. 2. in the accessors call EnterCriticalSection() emmediatley prior to the access, 
  5. 3, call LeaveCriticalSection() immediately following access, and finally
  6. 4. DeleteCriticalSection in class Destructor.
  7.  
  8. 1: http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx
  9. 2: http://msdn.microsoft.com/en-us/library/ms682608.aspx
  10. 3: http://msdn.microsoft.com/en-us/library/ms684169(VS.85).aspx
  11. 4: http://msdn.microsoft.com/en-us/library/ms682552(VS.85).aspx
Which is much faster than the equivalent mutex operation.

BTW the Lock keyword is a C# thing, that was extended by the CLR.
Without the CLR your application may have issues.

Happy Coding!
Jul 11 '08 #4
Sirmont
12
Very relevant comment. I understand why it would be more efficient to have one mutex/critical section per member. In fact I am very couscious of this, but the class I am making thread-safe is basically making operations on a map, so there's pretty much no gain to be made there.

What I don't understand is why should I use a critical section instead of a mutex and how it is different?

Thanks for your input!
J-O

P.-S. My Lock()/Unlock() methods were just examples. In fact I use wxWidgets, so I use wxLock/wxUnlock and wxCriticalSection.
Jul 16 '08 #5
Banfa
9,065 Expert Mod 8TB
A Critical Section is a more limited but lighter version of a mutex.

That is a Critical Section provides less functionality, it in only works inter-thread with-in a single process where as a mutex works inter-process and a critical section is not a OS object so you can't use the Wait... functions to wait on it which you can with a mutex.

However the loss of functionality results in a performance gain, it is quicker to lock/unlock a critical section compared to a mutex.
Jul 17 '08 #6
Sirmont
12
Great! Thanks guys! This answers it all...
Jul 24 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Chris Mantoulidis | last post by:
Forgive me if I'm wrong but I think there is something like an extra member scope in classes. for example: class abc { ostream & operator << (ostream &, const abc &); istream & operator >>...
10
by: Not Available | last post by:
On the host server: namespace JCart.Common public class JCartConfiguration : IConfigurationSectionHandler private static String dbConnectionString; public static String ConnectionString { get...
10
by: Jeff Grills | last post by:
I am an experienced C++ programmer with over 12 years of development, and I think I know C++ quite well. I'm changing jobs at the moment, and I have about a month between leaving my last job and...
5
by: Ajay Pal Singh | last post by:
Hi, I've one question related to singelton implementation of a class. Suppose a class is as Singelton and contains a public method. If there are more than one requests for the same method...
2
by: John Mullin | last post by:
We are having a problem which appears similar to a previous posting: http://groups.google.com/groups?hl=en&lr=&frame=right&th=d97f552e10f8c94c&seekm=OZw33z9EDHA.2312%40TK2MSFTNGP10.phx.gbl#link1 ...
3
by: Diffident | last post by:
Hello All, Following is a static method. Can you please tell me if this is threadsafe...why? If it is not threadsafe...why? Thank you. public static string...
84
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
12
by: hweekuan | last post by:
hi, it seems i can't assign the const variable u in class A, one way to solve the problem may be to build a copy constructor. however, why does C++ or vector class not like this code? my g++ is:...
6
by: Gaijinco | last post by:
I'm trying to do a template class Node. My node.hpp is: #ifndef _NODE_HPP_ #define _NODE_HPP_ namespace com { namespace mnya { namespace carlos { template <typename T>
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.