Thread synchronization
-
Hi there! The thing I would like to know is how to lock and unlock a single variable, such as int or double? All these semaphores and events must be declared within a class, but how can I do it with simple types?
You still have to use at least a Critical Section to lock against while accessing the simple type. Ant. I'm hard, yet soft.
I'm coloured, yet clear.
I'm fruity and sweet.
I'm jelly, what am I? Muse on it further, I shall return! - David Williams (Little Britain) -
You still have to use at least a Critical Section to lock against while accessing the simple type. Ant. I'm hard, yet soft.
I'm coloured, yet clear.
I'm fruity and sweet.
I'm jelly, what am I? Muse on it further, I shall return! - David Williams (Little Britain)Hmm, I've found InterlockedExchange and I guess that's what I need. By the way, what will happen if I read variable's value in one thread and write to it from another thread using InterlockedExchange, something like this: bool yes_no; //Common variable void Thread1Func() { bool tmp; tmp=yes_no; } void Thread2Func() { InterlockedExchange((LPLONG)&yes_no,true); } So, if thread 1 get's to yes_no first is it going to work correctly?
-
Hmm, I've found InterlockedExchange and I guess that's what I need. By the way, what will happen if I read variable's value in one thread and write to it from another thread using InterlockedExchange, something like this: bool yes_no; //Common variable void Thread1Func() { bool tmp; tmp=yes_no; } void Thread2Func() { InterlockedExchange((LPLONG)&yes_no,true); } So, if thread 1 get's to yes_no first is it going to work correctly?
Assuming that Thread 1 has to wait until Thread 2 has updated the data then no it is not guaranteed to work. Have you thought about using events? Wait for the event in Thread 1 (before the read of the variable) then signal the event in Thread 2 after the variable update. This will ensure the data is current when Thread 1 comes to read it. Ant. I'm hard, yet soft.
I'm coloured, yet clear.
I'm fruity and sweet.
I'm jelly, what am I? Muse on it further, I shall return! - David Williams (Little Britain)