Date: 02-16-2022
Return to Index
created by gbSnippets
'The whole point of a thread is to allow 2 or more sections of code to run
'in parallel. This is particularly useful when intensive calculations (usually
'in loops) need to be made in the background - allowing the user to continue
'to operate an application while the background processing takes place.
'When a thread is created, using "Thread Create", it directs Windows to
'run a specific function. When that function completes, the thread ends.
'Like any function, the thread function can call other functions. But eventually
'execution returns to the thread, the function ends, and the thread ends.
'A thread has both a thread ID and a thread handle. The thread handle
'is used with the various PowerBASIC thread statements. The thread ID
'(from the THREADID statement) is used with more advanced thread-related API.
'There are no messages sent by Windows when a thread is created/closed,
'but see http://gbl_00349 for information on generating custom thread messages.
'Primary Code:
'There are 2 basic pieces to the puzzle:
'Create a thread Function to run as the thread
Thread Function NewThread (ByVal x As Long) As Long
'... thread code goes here
End Function
'Create the thread
Thread Create NewThread(0) To hThread
'Compilable Example: (Jose Includes)
#Compiler PBWin 9, PBWin 10
#Compile EXE
#Dim All
%Unicode=1
#Include "Win32API.inc"
Global hDlg as Dword
Function PBMain() As Long
Dialog New Pixels, 0, "Test Code",300,300,200,200, %WS_OverlappedWindow To hDlg
Control Add Button, hDlg, 100,"Start Thread", 50,10,100,20
Control Add Label, hDlg, 200,"<1st thread count>", 50,40,100,20
Control Add Label, hDlg, 300,"<2nd thread count>", 50,70,100,20
Dialog Show Modal hDlg Call DlgProc
End Function
CallBack Function DlgProc() As Long
If CB.Msg = %WM_Command AND CB.Ctl = 100 AND CB.Ctlmsg = %BN_Clicked Then
Local hThread as Dword
Thread Create NewThread(200) To hThread 'start the new thread, argument is control ID
Thread Close hThread To hThread
Thread Create NewThread(300) To hThread 'start the new thread, argument is control ID
Thread Close hThread To hThread
End If
End Function
Thread Function NewThread (ByVal x As Long) As Long
Local iCount&, hControl as Dword, tempZ as AsciiZ * 200
Control Handle hDlg, x To hControl
Do
Incr iCount&
tempZ = "Thread" + Str$(iCount&)
' Control Set Text hDlg, x, tempZ
PostMessage hControl, %WM_SETTEXT, 0 , ByVal VarPTR(tempz)
' SendMessage hControl, %WM_SETTEXT, 0 , ByVal VarPTR(tempz)
Loop Until iCount& > 2000
End Function
'gbs_00345
'Date: 03-10-2012
http://www.garybeene.com/sw/gbsnippets.htm