Return to Index
created by gbSnippets
'Windows supports a variety of ways to coordinate multiple execution
'threads and to provide synchronized access to resources, such as
'synchronization objects or mutex objects. This snippet deals with
'using a synchronization object to pause a thread.
'A synchronization object is an object whose handle can be specified
'in one of the wait API functions to coordinate the execution of multiple
'threads. More than one process can have a handle to the same
'synchronization object, making interprocess synchronization possible.
'The state of a synchronization object is either signaled Or nonsignaled.
'The wait functions allow a thread to block its own execution until a
'specified nonsignaled object is set to the signaled State.
'The system closes the handle automatically when the process terminates.
'The event object is destroyed when its last handle has been closed.
'Useful Wait API
CreateEvent 'creates an event object
SetEvent/ResetEvent 'set/reset event object to/from signalled state
WaitforSingleObject 'waits until object is in signalled state
'or until the time-out interval elapses
CloseHandle 'closes the handle
'The use of a synchronization object consumes far less system resources,
'than solutions such as simple Do-Loop which is used to act as a delay.
'These lines of code create a synchronization obect and change
'its signalled state.
Local iObject as Long
iObject = CreateEvent(ByVal 0,ByVal 1, ByVal 0, ByVal 0) 'default security, manual reset
'not-signalled, no name
SetEvent iObject 'sets synchronization objects state to signalled
ReSetEvent iObject 'sets synchronization objects state to non-signalled
CloseHandle iObject 'closes handle to synchronization objects
'In this example, a thread is created and uses a synchronization object to
'determine whether to execute a code loop. A global variable is used to
'stop the thread.
#Compiler PBWin 9, PBWin 10
Global hDlg As DWord, hThread As Long, iObject As Long, PleaseStopThread&
Function PBMain() As Long
Dialog New Pixels, 0, "Test Code",300,300,200,200, %WS_OverlappedWindow To hDlg
Control Add Button, hDlg, 100,"Start Counting", 50,10,100,20
Control Add Button, hDlg, 200,"Stop Counting", 50,40,100,20
Control Add Label, hDlg, 300,"<empty>", 50,70,100,20
Control Add Button, hDlg, 400,"Stop Thread", 50,100,100,20
Dialog Show Modal hDlg Call DlgProc
CallBack Function DlgProc() As Long
Local iJunk As Long
Select Case CB.Msg
iObject = CreateEvent(ByVal 0,ByVal 1, ByVal 0, ByVal 0) 'default security,Manual Reset, Initially not-signalled, no name
Thread Create myThreadFunction(iJunk) To hThread
Thread Close hThread to hThread
If CB.Ctl = 100 Then SetEvent iObject
If CB.Ctl = 200 Then ReSetEvent iObject
If CB.Ctl = 400 Then PleaseStopThread& = 1
Thread Function myThreadFunction(ByVal iJunk As Long) As Long
Static iCount As Long
WaitForSingleObject iObject, %INFINITE
Control Set Text hDlg, 300, Str$(iCount)
Loop Until PleaseStopThread&
created by gbSnippets