Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Problems with Sleep() in thread

Problems with Sleep() in thread

Scheduled Pinned Locked Moved C / C++ / MFC
question
29 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Stephen Hewitt

    Posting a message puts it in a queue; the speed at which the messages are removed from the queue by the receiving thread need not be directly related to the rate at which they're posted. For example, factors such as the time taken to process the message and thread scheduling come into play.

    Steve

    A Offline
    A Offline
    acerunner316
    wrote on last edited by
    #3

    Is there a way to accurately predict the actual time it takes to post a message? The function I'm using is depended on that time. Is there another way I can force the function to execute at specified time intervals, and accurately? Is there something like time() that would return ms instead of seconds?

    S C 2 Replies Last reply
    0
    • A acerunner316

      Is there a way to accurately predict the actual time it takes to post a message? The function I'm using is depended on that time. Is there another way I can force the function to execute at specified time intervals, and accurately? Is there something like time() that would return ms instead of seconds?

      S Offline
      S Offline
      Stephen Hewitt
      wrote on last edited by
      #4

      acerunner316 wrote:

      Is there a way to accurately predict the actual time it takes to post a message?

      It doesn't take long to post a message as it's simply queued. The delay comes into play because of the contents of the queue, the speed at which the receiving thread calls GetMessage and processes the message and thread scheduling.

      acerunner316 wrote:

      Is there another way I can force the function to execute at specified time intervals, and accurately?

      Probably the most accurate way would be to use a dedicated high priority thread which calls the function directly then sleeps, in a loop. Naturally if the approach is feasible or not in your case depends on what your function does.

      acerunner316 wrote:

      there something like time()

      Check out GetTickCount.

      Steve

      A 1 Reply Last reply
      0
      • A acerunner316

        Is there a way to accurately predict the actual time it takes to post a message? The function I'm using is depended on that time. Is there another way I can force the function to execute at specified time intervals, and accurately? Is there something like time() that would return ms instead of seconds?

        C Offline
        C Offline
        Chris Losinger
        wrote on last edited by
        #5

        acerunner316 wrote:

        Is there a way to accurately predict the actual time it takes to post a message?

        no. and your process could get preempted at any time.

        acerunner316 wrote:

        Is there another way I can force the function to execute at specified time intervals, and accurately?

        not really. WM_TIMER isn't very accurate (or reliable).

        acerunner316 wrote:

        Is there something like time() that would return ms instead of seconds?

        QueryPerformanceCounter[^] might help with that.

        image processing toolkits | batch image processing | blogging

        J 1 Reply Last reply
        0
        • A acerunner316

          I am using Sleep(10) in my thread to post a windows message every 10ms. In the function responding to the windows message, I find that it is being executed approximately every 16ms. Where does the 6ms delay come from? My computer is not the best 1.53GHz, but 6ms delay is still way too slow.

          M Offline
          M Offline
          Mark Salsbery
          wrote on last edited by
          #6

          To add to the other responses... There's also the Multimedia Timer Functions[^] Larry Osterman[^] has reported Windows timer accuracy findings in the OS source code for some time but this fairly new article is the first time I've seen it documented by Microsoft: Inside Windows NT High Resolution Timers[^]

          1 Reply Last reply
          0
          • S Stephen Hewitt

            acerunner316 wrote:

            Is there a way to accurately predict the actual time it takes to post a message?

            It doesn't take long to post a message as it's simply queued. The delay comes into play because of the contents of the queue, the speed at which the receiving thread calls GetMessage and processes the message and thread scheduling.

            acerunner316 wrote:

            Is there another way I can force the function to execute at specified time intervals, and accurately?

            Probably the most accurate way would be to use a dedicated high priority thread which calls the function directly then sleeps, in a loop. Naturally if the approach is feasible or not in your case depends on what your function does.

            acerunner316 wrote:

            there something like time()

            Check out GetTickCount.

            Steve

            A Offline
            A Offline
            acerunner316
            wrote on last edited by
            #7

            Stephen Hewitt wrote:

            Probably the most accurate way would be to use a dedicated high priority thread which calls the function directly then sleeps, in a loop. Naturally if the approach is feasible or not in your case depends on what your function does.

            The reason I am posting a message and not directly calling the function is because the function references members of the main class, and I remember reading somewhere that you can't do that in a thread. So how can I create a dedicated thread that calls the function directly. Thanks.

            S 1 Reply Last reply
            0
            • C Chris Losinger

              acerunner316 wrote:

              Is there a way to accurately predict the actual time it takes to post a message?

              no. and your process could get preempted at any time.

              acerunner316 wrote:

              Is there another way I can force the function to execute at specified time intervals, and accurately?

              not really. WM_TIMER isn't very accurate (or reliable).

              acerunner316 wrote:

              Is there something like time() that would return ms instead of seconds?

              QueryPerformanceCounter[^] might help with that.

              image processing toolkits | batch image processing | blogging

              J Offline
              J Offline
              Jorgen Sigvardsson
              wrote on last edited by
              #8

              Chris Losinger wrote:

              QueryPerformanceCounter[^] might help with that.

              I think that's shooting a bit over the top. GetTickCount() is probably just about right for what he's trying to time.

              -- Not based on the Novel by James Fenimore Cooper

              C 1 Reply Last reply
              0
              • A acerunner316

                Stephen Hewitt wrote:

                Probably the most accurate way would be to use a dedicated high priority thread which calls the function directly then sleeps, in a loop. Naturally if the approach is feasible or not in your case depends on what your function does.

                The reason I am posting a message and not directly calling the function is because the function references members of the main class, and I remember reading somewhere that you can't do that in a thread. So how can I create a dedicated thread that calls the function directly. Thanks.

                S Offline
                S Offline
                Stephen Hewitt
                wrote on last edited by
                #9

                That's not an easy question to answer without detailed knowledge about what you're trying to do and how you've gone about doing it.

                Steve

                A 1 Reply Last reply
                0
                • S Stephen Hewitt

                  That's not an easy question to answer without detailed knowledge about what you're trying to do and how you've gone about doing it.

                  Steve

                  A Offline
                  A Offline
                  acerunner316
                  wrote on last edited by
                  #10

                  Basically, my program is sampling data from an external USB device. The data is displayed in the window as well as logged to a file. I want to sample and log the data at a specified sampling rate. In this case, I chose every 10ms. The retrieval in done through API calls in the function that's responding to the windows message posted by the thread. My logic was that if I post the message every 10ms, the function will run every 10ms and therefore sampling rate will be 10ms. Clearly, this is not the case. Hopefully that clears things up.

                  S 1 Reply Last reply
                  0
                  • A acerunner316

                    Basically, my program is sampling data from an external USB device. The data is displayed in the window as well as logged to a file. I want to sample and log the data at a specified sampling rate. In this case, I chose every 10ms. The retrieval in done through API calls in the function that's responding to the windows message posted by the thread. My logic was that if I post the message every 10ms, the function will run every 10ms and therefore sampling rate will be 10ms. Clearly, this is not the case. Hopefully that clears things up.

                    S Offline
                    S Offline
                    Stephen Hewitt
                    wrote on last edited by
                    #11

                    There are a number of approaches I'd consider: The first is to abandon the idea of having “super accurate” callbacks. Instead just use a reasonably accurate mechanism, such as SetTimer or your current scheme, but record the time of each sample along with the sample data. The second would be to use a high priority thread like I described earlier to do all the sampling and fill buffers which can be accessed by the UI thread – with appropriate synchronization. On a side note be aware that posting messages from another thread is probably only marginally more accurate then using SetTimer.

                    Steve

                    A 1 Reply Last reply
                    0
                    • J Jorgen Sigvardsson

                      Chris Losinger wrote:

                      QueryPerformanceCounter[^] might help with that.

                      I think that's shooting a bit over the top. GetTickCount() is probably just about right for what he's trying to time.

                      -- Not based on the Novel by James Fenimore Cooper

                      C Offline
                      C Offline
                      Chris Losinger
                      wrote on last edited by
                      #12

                      he was talking about accuracy in the 10-20ms range. GetTickCount can't get near that.

                      image processing toolkits | batch image processing | blogging

                      J 1 Reply Last reply
                      0
                      • S Stephen Hewitt

                        There are a number of approaches I'd consider: The first is to abandon the idea of having “super accurate” callbacks. Instead just use a reasonably accurate mechanism, such as SetTimer or your current scheme, but record the time of each sample along with the sample data. The second would be to use a high priority thread like I described earlier to do all the sampling and fill buffers which can be accessed by the UI thread – with appropriate synchronization. On a side note be aware that posting messages from another thread is probably only marginally more accurate then using SetTimer.

                        Steve

                        A Offline
                        A Offline
                        acerunner316
                        wrote on last edited by
                        #13

                        well, it doesn't have to be super accurate, but 6ms delay out of the specified 10ms is huge. 1 or 2 ms might be acceptable. Can you explain how I would use SetTimer to solve my problem, where would I call it? Also can you explain how to use a high priority thread. Would I be able to access member variables/functions of the main class? Does it operate differently than a worker thread.

                        S 1 Reply Last reply
                        0
                        • A acerunner316

                          well, it doesn't have to be super accurate, but 6ms delay out of the specified 10ms is huge. 1 or 2 ms might be acceptable. Can you explain how I would use SetTimer to solve my problem, where would I call it? Also can you explain how to use a high priority thread. Would I be able to access member variables/functions of the main class? Does it operate differently than a worker thread.

                          S Offline
                          S Offline
                          Stephen Hewitt
                          wrote on last edited by
                          #14

                          acerunner316 wrote:

                          Can you explain how I would use SetTimer to solve my problem, where would I call it?

                          Calling SetTimer wouldn't solve your problem. I was just pointing out that using SetTimer instead of posting messages from a worker thread would be simpler and only marginally less accurate.

                          acerunner316 wrote:

                          Also can you explain how to use a high priority thread. Would I be able to access member variables/functions of the main class? Does it operate differently than a worker thread.

                          When I said a "high priority" thread I simply meant a worker thread with a high priority. A thread's priority can be set using SetThreadPriority. Normally having a thread with a really high priority is a bad idea but since our thread spends most or its life asleep and when it is awake just takes a sample then goes back to sleep it’s ok. In this context the high priority is just to reduce the scheduling overhead so that our thread is chosen by the scheduler earlier than others when the sleep time has expired. As to accessing member variables of a class that’s a complex question which would require more detailed knowledge of your application.

                          Steve

                          1 Reply Last reply
                          0
                          • A acerunner316

                            I am using Sleep(10) in my thread to post a windows message every 10ms. In the function responding to the windows message, I find that it is being executed approximately every 16ms. Where does the 6ms delay come from? My computer is not the best 1.53GHz, but 6ms delay is still way too slow.

                            T Offline
                            T Offline
                            ThatsAlok
                            wrote on last edited by
                            #15

                            acerunner316 wrote:

                            I am using Sleep(10) in my thread to post a windows message every 10ms.

                            Sleep(10) doesn't sleep your thread fro 10 ms, as windows is not realtime system... actually it sleep time range between 10 ms to 54 ms depending on current load on the system and processor speed

                            "Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow

                            cheers, Alok Gupta VC Forum Q&A :- I/ IV Support CRY- Child Relief and you

                            1 Reply Last reply
                            0
                            • A acerunner316

                              I am using Sleep(10) in my thread to post a windows message every 10ms. In the function responding to the windows message, I find that it is being executed approximately every 16ms. Where does the 6ms delay come from? My computer is not the best 1.53GHz, but 6ms delay is still way too slow.

                              J Offline
                              J Offline
                              Joe Woodbury
                              wrote on last edited by
                              #16

                              Generally Windows NT and later have a timer interrupt of 10ms. However the HAL for some systems has set it to use 15ms. This means you can't sleep for less than that amount using the timeouts for Sleep() and Wait...() calls.

                              Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke

                              1 Reply Last reply
                              0
                              • A acerunner316

                                I am using Sleep(10) in my thread to post a windows message every 10ms. In the function responding to the windows message, I find that it is being executed approximately every 16ms. Where does the 6ms delay come from? My computer is not the best 1.53GHz, but 6ms delay is still way too slow.

                                K Offline
                                K Offline
                                kasturi_haribabu
                                wrote on last edited by
                                #17

                                1. Are you sure your function which is posting message takes '0'ms to execute ? I raise this question because, if your calling code has a lot to do and then sleep 10 ms, the interval between subsequent calls would be (Sleep time + Time taken to execute other part of the function). If you are very specific about the response time, i dont think post message is the right way to address such issuesbecause the latency of the response is not guaranted. You can use Events or a Semaphore-give-release technique to decrease the latency further. but the technique you need to choose depends on your applcation. Haribabu.

                                A 1 Reply Last reply
                                0
                                • A acerunner316

                                  I am using Sleep(10) in my thread to post a windows message every 10ms. In the function responding to the windows message, I find that it is being executed approximately every 16ms. Where does the 6ms delay come from? My computer is not the best 1.53GHz, but 6ms delay is still way too slow.

                                  S Offline
                                  S Offline
                                  S Douglas
                                  wrote on last edited by
                                  #18

                                  acerunner316 wrote:

                                  but 6ms delay is still way too slow

                                  To get an understanding of how time works read Time is the Simplest Thing[^]


                                  I'd love to help, but unfortunatley I have prior commitments monitoring the length of my grass. :Andrew Bleakley:

                                  1 Reply Last reply
                                  0
                                  • C Chris Losinger

                                    he was talking about accuracy in the 10-20ms range. GetTickCount can't get near that.

                                    image processing toolkits | batch image processing | blogging

                                    J Offline
                                    J Offline
                                    Jorgen Sigvardsson
                                    wrote on last edited by
                                    #19

                                    So.. uh, the system timer resolution is too low? Lucky me that I don't have to do anything multimedia related, because I was under the impression that a timer which is given the attribute system would be the most accurate one. Thanks for the heads up - who knows? I might have to deal with issues like this some day...

                                    -- Verletzen zerfetzen zersetzen zerstören Doch es darf nicht mir gehören Ich muss zerstören

                                    C 1 Reply Last reply
                                    0
                                    • J Jorgen Sigvardsson

                                      So.. uh, the system timer resolution is too low? Lucky me that I don't have to do anything multimedia related, because I was under the impression that a timer which is given the attribute system would be the most accurate one. Thanks for the heads up - who knows? I might have to deal with issues like this some day...

                                      -- Verletzen zerfetzen zersetzen zerstören Doch es darf nicht mir gehören Ich muss zerstören

                                      C Offline
                                      C Offline
                                      Chris Losinger
                                      wrote on last edited by
                                      #20

                                      it's updated every ~15ms to 50ms (depending on the version of Windows). so, it is measuring time in the ms range, but the difference between two consecutive calls will never be less than ~15ms. QueryPerformanceCounter is much more accurate.

                                      image processing toolkits | batch image processing | blogging

                                      A 1 Reply Last reply
                                      0
                                      • K kasturi_haribabu

                                        1. Are you sure your function which is posting message takes '0'ms to execute ? I raise this question because, if your calling code has a lot to do and then sleep 10 ms, the interval between subsequent calls would be (Sleep time + Time taken to execute other part of the function). If you are very specific about the response time, i dont think post message is the right way to address such issuesbecause the latency of the response is not guaranted. You can use Events or a Semaphore-give-release technique to decrease the latency further. but the technique you need to choose depends on your applcation. Haribabu.

                                        A Offline
                                        A Offline
                                        acerunner316
                                        wrote on last edited by
                                        #21

                                        I don't know if it takes 0ms, but there is nothing else to my code other than repeatedly posting messages. UINT CNOx1000MonitorDlg::FThreadLoop (LPVOID PptrToClass) { CMainWindowDlg *LptrClass = static_cast(PptrToClass); HWND *ptrWindowHandle = new HWND; *ptrWindowHandle = LptrClass->GetSafeHwnd(); while(LptrClass->mbolThreadExecute) { ::PostMessage(*ptrWindowHandle, WM_UPDATE_CONTROLS, 0, 0); ::Sleep(10); } delete ptrWindowHandle; return 0; }

                                        1 Reply Last reply
                                        0
                                        • C Chris Losinger

                                          it's updated every ~15ms to 50ms (depending on the version of Windows). so, it is measuring time in the ms range, but the difference between two consecutive calls will never be less than ~15ms. QueryPerformanceCounter is much more accurate.

                                          image processing toolkits | batch image processing | blogging

                                          A Offline
                                          A Offline
                                          acerunner316
                                          wrote on last edited by
                                          #22

                                          How will I use QueryPerformanceCounter as a way of sampling data? I will still need a thread to loop a function call. And in that function will check QueryPerformanceCounter. But if posting a message takes longer than 6ms. Then QueryPerformanceCounter can only be as accurate as that. Can you provide a code sample? Im fairly new to windows programming. I am basically learning from sample code that I find online. Thanks.

                                          C 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups