It's not a broken program, just a question about multi-threading that's been puzzling me all day. I must have made a mistake in my logic somewhere or there's something I don't know about how CPUs/Windows work. Why do integers shared between threads not need a mutex? I'll show you what I mean.
Check out this program:
Code: Select all
Procedure ThreadProc(*dat.Long)
*dat\l = *dat\l * 5
EndProcedure
Define Thread.l
Define Value.l
Value = 1
Thread = CreateThread(@ThreadProc(),@Value)
Value = Value * 5
WaitThread(Thread)
OpenConsole()
PrintN("Value = " + Str(Value))
Input()
I compiled it with the command line:
Code: Select all
pbcompiler tt.pb /THREAD /COMMENTED
The variable 'Value' initially contains 1. Both threads multiply it by 5, giving a result (as expected) of 25. But a thread can be interrupted at any time, right? So if the new thread was interrupted at the point I've indicated in the asm output, both threads would find 'Value' to contain 1, both would multiply it by 5 and both would replace 5 on the stack... giving the wrong answer.
Code: Select all
; multiplication code from the second thread
; *dat\l = *dat\l * 5
MOV ebp,dword [esp+PS0+0]
MOV ebx,dword [ebp]
; say it switches back to the main thread now
IMUL ebx,5
PUSH ebx
MOV ebp,dword [esp+PS0+4]
POP eax
MOV dword [ebp],eax
; multiplication code from the main thread
; Value = Value * 5
MOV ebx,dword [v_Value]
IMUL ebx,5
MOV dword [v_Value],ebx
I've tried running it thousands of times but it always prints 25. How does this work?



