Hello MASM32, So I was experimenting with thread and APCs and this code crashes, unable to figure out why it does :icon_eek:
any help? maybe I misunderstand how this works?
.586
.model flat,stdcall
include windows.inc
include kernel32.inc
includelib kernel32.lib
includelib msvcrt.lib
printf PROTO C :VARARG
.data
szthread CHAR "%u executing thread",13,10,0
szapc CHAR "%u executing apc",13,10,0
.code
apc proc
xor esi,esi
.while esi < 5
inc esi
push esi
push offset szapc
call printf
add esp, 8
invoke Sleep,1000
.endw
ret
apc endp
thread proc
invoke GetCurrentThread
invoke QueueUserAPC,apc,eax,0
xor edi, edi
xor esi, esi
.while edi < 5 ; 5 times
.while esi < 5
inc esi
push esi
push offset szthread
call printf
add esp, 8
invoke Sleep,1000
.endw
invoke SleepEx,3000,TRUE ; trigger apc
inc edi
.endw
ret
thread endp
entry proc
invoke CreateThread,0,0,thread,0,0,0
invoke CloseHandle,eax
entry endp
end entry
entry proc
invoke CreateThread,0,0,thread,0,0,0
invoke CloseHandle,eax
entry endp
never tried APC stuff
but - the above code has a couple problems
first, CreateThread returns immediately after creating the thread
you don't want to close the thread handle - you want the thread to terminate on it's own
secondly, the "entry" proc has no ExitProcess call
after CloseHandle returns, execution goes off into la-la land :P
Also,
invoke CreateThread,0,0,OFFSET thread,0,0,0
that one is ok as is
the assembler knows it's code, so OFFSET is not required
what may be required is a PROTOtype for the thread proc
that is, if the CreateThread call appears in the code before the thread function does
example...
INCLUDE \masm32\include\masm32rt.inc
;*************************************************************************************************************
Thrd PROTO
Func PROTO :DWORD
;*************************************************************************************************************
.CODE
_main PROC
xor edi,edi
INVOKE CreateThread,edi,edi,Thrd,500,edi,edi
INVOKE CreateThread,edi,edi,Thrd,400,edi,edi
INVOKE CreateThread,edi,edi,Thrd,600,edi,edi
INVOKE CreateThread,edi,edi,Thrd,100,edi,edi
INVOKE CreateThread,edi,edi,Thrd,300,edi,edi
INVOKE CreateThread,edi,edi,Thrd,200,edi,edi
inkey " "
exit
_main ENDP
;*************************************************************************************************************
Thrd PROC
INVOKE Func,[esp+4]
INVOKE ExitThread,0
Thrd ENDP
;*************************************************************************************************************
Func PROC USES EBX dwVal:DWORD
mov ebx,dwVal
INVOKE Sleep,ebx
print ustr$(ebx),32
ret
Func ENDP
;*************************************************************************************************************
END _main