Skip to main content
gamedev.net
🔒 Locked

Multithreaded programming question (theoretical)

Started by SpaceRogue Jul 17, 2003 at 10:00 PM 4 replies 800+ views
Original Post
SpaceRogue
SpaceRogue
Normally I know you would want to use synchronization objects like a mutex, or critical section if you need a variable modified by two or more threads, but is it ALWAYS necessary? If I have a simple integer variable that will be incremented periodically by different threads, is it really necessary to protect the variable with a synchronization object even if I have no conditionals depending on the variable's value (I'm using it purely for informational purposes)? In other words, is it possible two threads could 'corrupt' the value by accessing it simultaneously, or (since it is a simple increment) will it be ok? [edited by - SpaceRogue on July 17, 2003 11:19:35 PM]
SpaceRogue
SpaceRogue
I already know about InterlockedIncrement...thanks anyway.

Theoretically : I'd like to know what the possibilities are. Edit: It's my understanding that making the variable volatile should be all that is needed to prevent corruption. Am I correct?


[edited by - SpaceRogue on July 17, 2003 11:30:46 PM]
cmptrgear
cmptrgear
The biggest problem would be that it wouldnt catch all of the increments.

Say you have two threads and variable a=5
One thread increments the variable
a=6

Before the variable gets stored the second thread interrupts and increments the variable
a=6 because a in memory is still 5
a is stored in memory so a=6

the first thread finishes and stores a(6) in memory but since both threads incremented the variable it should be 7

"I may not agree with what you say but I will defend to the death your right to say it."
--Voltaire
"Pfft, Facts! Facts can be used to prove anything!" -- Homer J. Simpson
Gizz
Gizz
I don''t think there should be any problem using a simple type variable which does not hold critical information. Even if you get "old" information it should not affect you.

As for the possibility of having corrupted data, on a single processor machine for a simple type, I don''t think it could happen ( only one operation to affect a value to an int ) .

Cheer
SpaceRogue
SpaceRogue
Thanks, hmm...that makes sense.

[edited by - SpaceRogue on July 17, 2003 11:39:56 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.