Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Guys,

I know its very simple and basic question thought would like to know answer.
I am newbie in threading concepts.

Question: Suppose, I have a bool variable lets say bool var, Two threads can use this variable.

How should I synchronize it?

As per my knowledge goes,we can use mutex to lock variable. This will ensure that when a variable is getting used by a thread, other thread will can not access it.


What are other solutions.

Please help.

Regards,
Joy
Posted

1 solution

Consider using "The scoped locking idiom". It is described (among many other places) at http://www.cs.wustl.edu/~schmidt/PDF/ScopedLocking.pdf[^]

In general, you need:
1. A class that encapsulates your shared resource.
2. All public functions in the class acquire a lock at entry, and release it at exit, possibly using the aforementioned idiom.

In Windows, the API exposes some functions to avoid the overhead for simple cases: for instance, OverlockedIncrement and OverlockedDecrement for integers.

If it's important for you, google also "lock free threading patterns".

Hope this helps,

Pablo.
 
Share this answer
 
Comments
joyjhonson 24-Apr-14 5:41am    
sure will gogle on "Lock free threading patterns". Thanks

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