I am very new to multithreading. So my question is
How can we check if any method needs threads safety or not, Or in other words if the code is thread safe or not. For e.g
int Foo ()
int i = 10;
cout << i <<endl;
Is this a thread safe? If yes why, if Not Why?
How should we check yes this function need thread safety or not?
It will be highly appreciable,If somebody can explain with few simple examples.
Thanks in advance
Edited 29-Jan-13 19:01pm
Thread-safe issues will come up anywhere you have the potential for two or more threads (or processes or instructions or...) that can have concurrent access to an object at the same time, and at least one of those accesses is a 'write'. In the code example you provide, there is no race condition with 'i' but there might be with the stream object that accesses cout.
Thread safety is an issue is a function uses shared resources (that can be anything from a variable to a file on disk). Access to those shared resources must be synchronized, for a function to be considered thread-safe. Otherwise, race conditions can appear and lead to undexpected behavior.
Now, your function is not thread safe because it uses cout, which is an object that streams output to a console. This is a shared resource, and you should sync the access to it.
This is implementation-specific. It is possible that the cout-stream is threadsafe, ask your compiler-vendor, or read the manual. Nevertheless there is no requirement for it to be, by the standard.
For the variable "int i" it is easy. It is local to the thread starting "int Foo()", which needs to return an int btw.
Marius said the rest. Thread-Safety means that ressources being in access by multiple threads but are only allowed to be in access by one single thread at a time need to be secured.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)