I'm working on creating a call back function for an ASP.NET cache item removal event.
The documentation says I should call a method on an object or calls I know will exist (will be in scope), such as a static method, but it said I need to ensure the static is thread safe.
Part 1: What are some examples of things I could do to make it un-thread safe?
Part 2: Does this mean that if I have
static int addOne(int someNumber){ int foo = someNumber; return foo +1; }
and I call Class.addOne(5); and Class.addOne(6); simutaneously, Might I get 6 or 7 returned depending on who which invocation sets foo first? (i.e. a race condition)
C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
The boolean operators function in a similar way to the comparison operators: each returns 0 if evaluates to FALSE or 1 if it evaluates to TRUE.
The statement inside the if block are executed only when condition is true, otherwise not. If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute.
That addOne function is indeed thread safe because it doesn't access any data that could be accessed by another thread. Local variables cannot be shared among threads because each thread gets its own stack. You do have to make sure, however, that the function parameters are value types and not reference types.
static void MyFunction(int x) { ... } // thread safe. The int is copied onto the local stack. static void MyFunction(Object o) { ... } // Not thread safe. Since o is a reference type, it might be shared among multiple threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With