473,587 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is pass by reference thread safe?

Hi,
If I have this function

void DoSomething(int & index)
{
::Sleep(10000);
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?

Thanks
Jul 23 '05 #1
9 5607
Andy Chang wrote:
Hi,
If I have this function

void DoSomething(int & index)
{
::Sleep(10000);
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?

Stock answer: C++ has no concepts of threads, so your question is not
topical here.

Past that, think about it logically: if multiple threads of execution
refer to the same variable (as is the case here; remember, the whole
point of references is that they are aliases to already existing objects).

HTH,
--ag
--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Jul 23 '05 #2
Andy Chang wrote:
Hi,
If I have this function

void DoSomething(int & index)
{
::Sleep(10000);
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?

Stock answer: C++ has no concepts of threads, so your question is not
topical here.

Past that, think about it logically: If multiple threads of execution
refer to the same variable (as is the case here; remember, the whole
point of references is that they are aliases to already existing
objects), thread safety is determined by what you're doing in, say,
DoSomethingWith (), etc.

HTH,
--ag
--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Jul 23 '05 #3
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::DoS omething) );

Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omethingElse) );
//Start execution of ps->DoSomething( )
pthread1->Start();

//Start execution of ps->DoSomethingEls e()
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
Jul 23 '05 #4
Suppose DoSomething(int & index) is called with different indexes as in

DoSomething(giT hreadAIndex) and DoSomething(giT hreadBIndex) from two
threads, then the function is thread safe even without the monitor calls? I
mean there is no possibility that the call from thread A could modify thread
B's index and vice versa?

Sorry, I didn't know which group to post and this is rather important point
I need to clear out.

Thanks

"Ioannis Vranos" <iv*@remove.thi s.grad.com> wrote in message
news:1109734925 .342146@athnrd0 2...
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::DoS omething) );

Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omethingElse) );
//Start execution of ps->DoSomething( )
pthread1->Start();

//Start execution of ps->DoSomethingEls e()
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

Jul 23 '05 #5
Andy Chang wrote:
Suppose DoSomething(int & index) is called with different indexes as in

DoSomething(giT hreadAIndex) and DoSomething(giT hreadBIndex) from two
threads, then the function is thread safe even without the monitor
calls? I mean there is no possibility that the call from thread A
could modify thread B's index and vice versa?
As others have said, threads are OT. However, I think it is safe to say that
different threads executing DoSomething at the same time will have different
copies of local variables, including index. So Thread B could conceivably modify
the int referred to by thread A's copy of index during the execution of
DoSomething, but not via its own copy of index unless Thread A's index and
Thread B's happen to refer to the same int.
Sorry, I didn't know which group to post and this is rather important
point I need to clear out.
Try comp.programmin g.threads
Thanks


Jonathan
Jul 23 '05 #6
Andy Chang wrote:
Suppose DoSomething(int & index) is called with different indexes as in

DoSomething(giT hreadAIndex) and DoSomething(giT hreadBIndex) from two
threads, then the function is thread safe even without the monitor calls? I
mean there is no possibility that the call from thread A could modify thread
B's index and vice versa?
Yes, if the arguments are not related, then the operations are thread safe.

Sorry, I didn't know which group to post and this is rather important point
I need to clear out.

Which is your platform?

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #7
Ioannis Vranos wrote:
Yes, if the arguments are not related, then the operations
on them
are thread safe.


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #8
Andy Chang wrote:
Hi,
If I have this function

void DoSomething(int & index)
{
::Sleep(10000);
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?


It depends on where index is referencing.

// this below would unquestionably thread safe.
void DoSomething(int index)
{
::Sleep(10000);
DoSomethingWith (index);
}

However, since, in your example, index is passed in as a non-const
reference, it's impossible to tell what it referencing and what
DoSomethingWith (index) is going to do with it.
Jul 23 '05 #9
Andy Chang wrote:
If I have this function:

void DoSomething(int & index) {
::Sleep(10000);
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?


You are confused.
A *variable* is never "thread safe".
Your *code* "thread safe"
only if two different threads
cannot modify the same variable.
If you pass a non-const reference [index]
to an int variable shared by two or more threads,
your code is *not* "thread safe"
since the non-const reference implies that
the variable can be modified.

Please note that
people sometimes refer to code that is actually threaded --
code that employs mutual exclusion explicitly
to protect shared variables -- as "thread safe".
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1508
by: Timo | last post by:
I'm trying to make a thread safe object cache without locking. The objects are cached by the id of the data dict given in __new__. Objects are removed from the cache as soon as they are no longer referenced. The type of the data must be a Python dict (comes from an external source). Here's what I've got so far: import time
6
8298
by: GG | last post by:
Is this public static method thread safe. //Receives a file name as a parameter //and returns the contents of that file as a string public static string FileToStr(string fileName) { FileStream fStream=null; lock(fStream) //just in case we use it for multithreading to be thread safe {
4
2888
by: Chris Newby | last post by:
When accessing, for example, an object stored in the session such as: Session.MyProperty = "Some Value"; Is access to MyObject thread-safe?
7
17327
by: Alexander Walker | last post by:
Hello I want to get the value of a property of a control from a thread other than the thread the control was created on, as far as I can see this is not the same as invoking an operation on a control on a different thread I have used the following code as per the guidance in the msdn documentation to invoke an operation on a control from a...
1
10355
by: Macca | last post by:
Hi I have a N-tier ASP.NET application that uses a data access tier to get data from a database and pass it to the middleware/business tier for processing/filtering and then passes the modified data to the web tier for presentaion. What I would like to do is introduce a cache to the middleware tier to cut down on the round trips to the...
2
2149
by: lwhitb1 | last post by:
Does anyone have any input on setting up my CAB application so that the application is thread safe, and cached appropiately? I read that this can be managed through Services, and dynamic injection. On the contrary, I was told that this can be handled using Enterprise Library cached application block. Last, but not least, i read you can...
3
2530
by: tcomer | last post by:
Hello! I'm working on an asynchronous network application that uses multiple threads to do it's work. I have a ChatClient class that handles the basic functionality of connecting to a server and sending/ receiving messages. The problem is, some of the ChatClient methods access another ChatWindow class that is derived from a Form and that...
15
2755
by: Laser Lu | last post by:
I was often noted by Thread Safety declarations when I was reading .NET Framework Class Library documents in MSDN. The declaration is usually described as 'Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.' So, does this mean All the static/shared...
3
3068
by: andreas.zetterstrom | last post by:
I'm implementing some different c++ classes which I want to be thread safe. All these classes contain lists or arrays of some kind. I'm using protected sections to make them thread safe. The question then is: how do you in a nice safe way pick values out of the list? The easiest way is to have a pair of Lock, Unlock functions, but this also...
0
7920
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7849
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8347
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6626
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5394
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1454
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1189
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.