Announcement

Collapse
No announcement yet.

WaitForSingleObject/SetEvent

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • WaitForSingleObject/SetEvent

    Was discussing this with an engineer at work here...
    He suggested using the WaitForSingleObject up to the point that the new thread has acquired the atomic time back over thenetwork, thus we are waiting on a network return, after that release it wiht a SetEvent call..

    This is new to me, does anyone understand that?
    SetEvent requires an hEvent handle, where is that achieved from?

    Code:
    'In DialogProc:
        Case %WM_COMMAND
          Select Case LoWrd(wParam)
                 Case %IDM_ACHECK
                     Select Case CbCtlMsg
                         Case %BN_CLICKED
    
    
                   If IsFalse g_lngInitThreadHandle Then
                      Thread Create InitThread(id) To g_lngInitThreadHandle
                      Thread Close g_lngInitThreadHandle To Result
    '                      Select Case WaitForSingleObject(hDlg , %INFINITE)
    '                            Case %WAIT_OBJECT_0       ' The process terminated.
    '                            Case %WAIT_TIMEOUT       ' The process did not terminate within 5000 milliseconds.
    '                            Case %WAIT_ABANDONED       ' Bad call to function (invalid handle?)
    '                      End Select
    
                   End If
                End If
            Function = 0
            Exit Function
    
    Now thefunction, code removed to get to the point:
    '-----------------------------------------------------------------------------------
    Function InitThread(ByVal x As Long) As Long
    
    UTCTime = CheckAtomicTime(nServer,Val(AtomPort),aTimeOut, Delay,st)


    -------------
    Scott
    mailto:[email protected][email protected]</A>
    Scott Turchin
    MCSE, MCP+I
    http://www.tngbbs.com
    ----------------------
    True Karate-do is this: that in daily life, one's mind and body be trained and developed in a spirit of humility; and that in critical times, one be devoted utterly to the cause of justice. -Gichin Funakoshi

  • #2
    Scott --
    Look this sample. %INFINITIVE - means unlimited time
    Code:
       #Compile Exe
       #Register None
       #Dim All
       #Include "Win32Api.inc"
    
       Function MyThread (ByVal x As Long) As Long
          Local n As Long
          For n = 1 To 100: Sleep 500: Next
       End Function
    
       Function PbMain () As Long
          Local x As Long, idThread As Long
          Thread Create MyThread(x) To idThread
          Do
             Select Case WaitForSingleObject(idThread, 5000)
                ' Case %WAIT_ABANDONED :
                Case %WAIT_OBJECT_0  : MsgBox "Ok": Exit Do
                Case %WAIT_TIMEOUT   : MsgBox "Not yet"
             End Select
          Loop
          Thread Close idThread To idThread
       End Function
    PbMain starts thread and tests every 5 seconds thread is finished or not (thread - see Sleep - executes 50 sec).



    ------------------


    [This message has been edited by Semen Matusovski (edited April 17, 2000).]

    Comment


    • #3
      Yes, I'm not going crazy (That's like Yes, we have no banana's)...


      OK I understand this now, it's PERFECT for this specific example, as you can see that was test code, the %infinite was just in there, hadn't gotten around to a preset time, but I did put 3000 in the latest test and it worked for the most part, except when the clock returned in 250ms...

      Now the question is this.

      If my app NORMALLY takes say, 100-250 ms to complete the checking of the clock (hence the new thread), then setting the WaitForSingleObject to that should be fine...in the event it doesn't complete I will know and can start the thread over or at least calculate for it, but it also does allow me to place a maximim time limit on the Atomic clock checking, since anything greater than 1000ms could possibly indicate being wrong by a second.


      What about this SetEvent that our engineer spoke of?
      Is it required here? or does PB take care of that internally?


      Thanks

      Scott

      ------------------
      Scott
      mailto:[email protected][email protected]</A>
      Scott Turchin
      MCSE, MCP+I
      http://www.tngbbs.com
      ----------------------
      True Karate-do is this: that in daily life, one's mind and body be trained and developed in a spirit of humility; and that in critical times, one be devoted utterly to the cause of justice. -Gichin Funakoshi

      Comment


      • #4
        It doesn't test every 5, but checks for 5 seconds then if no, loops again. Not much difference from %INFINITE (my apologies to semen)

        My suggestion is to stay away from complex code if you are trying to synchronize clocks. Thread switching takes up cpu unless your target machine is dual processor, so do all your synchronization in one thread. WaitForSingleObject() is costly, also. If you must use multiple threads, use a critical section.


        ------------------

        Comment


        • #5
          Hi Scott

          WaitForSingleObject is getting a bad rap on this forum these days but it's quite useful - basically you want to wait for a given time out period or until the function, your atomic clock function in this case, returns - whichever is sooner.

          Here's a short snippet illustrating how you'd use it:

          Code:
          #COMPILE EXE
          
          #INCLUDE "win32api.inc"
          
          #IF NOT %DEF(%WAIT_FAILED)
          %WAIT_FAILED = &HFFFFFFFF???
          #ENDIF
          
          FUNCTION MyThread( BYVAL lEventHandle AS LONG ) AS LONG
             LOCAL i AS LONG
             
             FOR i = 0 TO 20
                 SLEEP 100
             NEXT
             
             'set the event to the signaled state
             CALL SetEvent( lEventHandle )
             
             FUNCTION = 1
             
          END FUNCTION
          
          FUNCTION PBMAIN() AS LONG
             LOCAL lHandle AS LONG
             LOCAL lResult AS LONG
             LOCAL lThreadHandle AS LONG
             
             'Create a non-signaled waitable event
                                    
             lHandle = CreateEvent( BYVAL %NULL, _ 'no security attributes
                                    0&, _ 'auto_reset event
                                    0&, _ 'non-signaled
                                    BYVAL %NULL _ 'no name since the event is not inheritable
                                    )
             THREAD CREATE MyThread( lHandle ) TO lThreadHandle
             
             'Wait until the function returns or a time-out of 3000 ms elapses
             '... whichever is sooner
             lResult = WaitForSingleObject( lHandle, 3000& )
             
             SELECT CASE lResult
                    CASE %WAIT_FAILED
                         MSGBOX "Wait failed - reason: " + STR$(GetLastError())
                    CASE %WAIT_OBJECT_0
                         MSGBOX "Function returned before time out"
                    CASE %WAIT_TIMEOUT
                         MSGBOX "Time out while waiting for function to return"
             END SELECT
             
             THREAD CLOSE lThreadHandle TO lResult
             
             CALL CloseHandle( lHandle ) 'close the event handle
             
          END FUNCTION
          ------------------

          Comment


          • #6
            If to have access to source code, I don't see reasons to use WFSO at all.
            For example, I have the app, which downloads files from Internet and execute TCP RECV in cycle.
            In thread I start Dialog Modal and user can press "Cancel" button.
            To understand that user pressed this button, I have global variable. When user presses this button, in callback(inside thread) I set Stop = 1.
            In main module I test this value after each TCP RECV.

            ------------------

            Comment


            • #7
              Hi Semen

              I personally like the WaitForSingleObject / CreateEvent / SetEvent combination: it makes for clean code and is resource efficient at least on NT 4.0 - I've never had any problems on Win9.x either.

              Of course it all depends what use you make of it - if you want to use WSFO in a polling loop then I think there may be more
              efficient alternatives depending on what your are waiting for: file I/O, events, port input, etc.

              In Scott's case where he wants to efficiently wait for a given period of time for a function to return I think WSFO is a good choice, since it enables waiting without setting/checking global flags which might need to be synchronized across threads.

              Cheers

              Florent

              ------------------

              Comment


              • #8
                You got it!

                Sine NIST time is so extremely accurate, and I want the timeserver to be as accurate as POSSIBlE for an Intel based machine, I absolutely have to know whether or not the clock returned within 1000ms, if it doesn't my DELAY will reflect that also, but I want redundancy, doing math doesn't always cut it, some days a timeout will cause it to be 1000ms (and another 10000 where it added to the seconds)...


                It's just to keep extremely accurate time, if it fails within 500ms at this point, I can NOT set the clock and risk being a few seconds off...

                All about network timing...


                Thanks!

                Now for WaitForMultipleObjects....(Just kidding!!)..

                Scott

                ------------------
                Scott
                mailto:[email protected][email protected]</A>
                Scott Turchin
                MCSE, MCP+I
                http://www.tngbbs.com
                ----------------------
                True Karate-do is this: that in daily life, one's mind and body be trained and developed in a spirit of humility; and that in critical times, one be devoted utterly to the cause of justice. -Gichin Funakoshi

                Comment

                Working...
                X