Andy Chang wrote:
Hi,
If I have this function
void DoSomething(int& index)
{
::Sleep(10000);
This has not much to do with thread safety itself.
DoSomethingWith(index);
}
Is the variable index thread safe? Meaning that if I call this from two
different threads, would each thread have its own copy of index?
Threads are off topic in clc++ since so far it is a system-specific
feature and not part of ISO C++. You will get more help in a newsgroup
about your platform.
In a lock based thread environment, and depending on how you have setup
your threads, above can be thread safe.
An example of the .NET multithreading model:
// .NET multithreading thread-lock model
__gc class SomeClass
{
int index;
//...
public:
// ...
void DoSomething()
{
Monitor::Enter(this);
// Modify index
Monitor::Exit();
}
void DoSomethingElse()
{
Monitor::Enter(this);
// Modify index
Monitor::Exit();
}
// ...
};
SomeClass *ps= __gc new SomeClass;
// ...
Thread *pthread1= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoSomething) );
Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoSomethingElse) );
//Start execution of ps->DoSomething()
pthread1->Start();
//Start execution of ps->DoSomethingElse()
pthread2->Start();
// ...
I have no experience with any other thread-style models or
multithreading in procedural paradigm.
But in a procedural lock-based model, I can guess you will do something
like this in your function:
void DoSomething(int& index)
{
Monitor::Enter(SOMETHING); // Or some lock function
// Modify index
Monitor::Exit(); // Or some unlock function
}
--
Ioannis Vranos
http://www23.brinkster.com/noicys