Wednesday, November 4, 2015

Sample Codes of Thread Safe functions and variables (ToDo....)

The simplest method is to make your variables private (but you do that already, right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

 Here is how to make variable thread safe in java. Make it private and accessible via synchronized public function call.
public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
{ 
count = amount;
}

public synchronized int getCount()
{
return count;
}
}


In C/C++, mutex, would be necessary.

No comments: