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
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Multithreading

Multithreading

Scheduled Pinned Locked Moved C / C++ / MFC
help
11 Posts 7 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.
  • A anilksingh

    IN a Dialog I have two CButton when i clicked on first button a loop starts. The requirement is when i click on second button it should break the loop. How i can communicate this to the loop. I tried Sleep so that i can check the status of common variable. But this variable is updatted only when the loop terminates. What will be the possible solution of my Problem.

    D Offline
    D Offline
    David Crow
    wrote on last edited by
    #2

    Read up on threads here and here.

    anilksingh wrote:

    I tried Sleep...

    Using Sleep() with threads is usually a bad idea.


    "The largest fire starts but with the smallest spark." - David Crow

    "Judge not by the eye but by the heart." - Native American Proverb

    1 Reply Last reply
    0
    • A anilksingh

      IN a Dialog I have two CButton when i clicked on first button a loop starts. The requirement is when i click on second button it should break the loop. How i can communicate this to the loop. I tried Sleep so that i can check the status of common variable. But this variable is updatted only when the loop terminates. What will be the possible solution of my Problem.

      _ Offline
      _ Offline
      _AnsHUMAN_
      wrote on last edited by
      #3

      one thing that you can do is that create a static flag=false as a global variable. now in the loop you can check that if the flag is set to true. (You will set the flag to true when the second button is pressed.) if the flag is set simply put return 0; in the block of code where you want the thread function to end. Here's some code for you that is inside the thread function :

      // Code inside the thread function and m_number is the 
      //variable for the edit box whose number property is set to true
      CMyDlg *test=(CMyDlg *)pVoid;
      	for(int i=0;i<1000;i++)
      	{
      		Sleep(10);
      		if(flag==true)
      		{
      			CString s;
      			s.Format ("%d",i);
      			AfxMessageBox("Thread stoping on "+ s);
      			return 0;
      		}
      		else
      		{
      			CString s;
      			s.Format ("%d",i);
      			test->m_number.SetWindowText (s);
      		}
      	}
      	return 0;
      

      Somethings seem HARD to do, until we know how to do them. ;-) _AnShUmAn_ -- modified at 9:34 Tuesday 13th June, 2006

      S 1 Reply Last reply
      0
      • A anilksingh

        IN a Dialog I have two CButton when i clicked on first button a loop starts. The requirement is when i click on second button it should break the loop. How i can communicate this to the loop. I tried Sleep so that i can check the status of common variable. But this variable is updatted only when the loop terminates. What will be the possible solution of my Problem.

        J Offline
        J Offline
        James R Twine
        wrote on last edited by
        #4

        The old way (Win16) of doing this was to pump messages in the loop so that the other button will respond to user input.  Today, a worker thread would be what I would suggest.    Look up how to create a background thread using the links provided in the previous answer.  While you can use a shared variable to terminate the thread, I would suggest looking into how "event" objects work with threads to get a feel for them and how they should be used.    Peace! -=- James


        If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
        Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
        DeleteFXPFiles & CheckFavorites (Please rate this post!)

        1 Reply Last reply
        0
        • A anilksingh

          IN a Dialog I have two CButton when i clicked on first button a loop starts. The requirement is when i click on second button it should break the loop. How i can communicate this to the loop. I tried Sleep so that i can check the status of common variable. But this variable is updatted only when the loop terminates. What will be the possible solution of my Problem.

          Z Offline
          Z Offline
          Zac Howland
          wrote on last edited by
          #5

          Create an event handle (using CreateEvent). Pass that handle to the loop when you create it (its quite common to pass such objects in the LPARAM pointer used when creating a thread). When you need to terminate the thread, call SetEvent. Internally to the loop, you will use WaitForSingleObject with an appropriate timeout value (in your case, 0 would probably work since you just want to check to make sure it has already been set). If WaitForSingleObject returns WAIT_OBJECT_0, then your event was signaled and you should stop the loop. Alternatively, you could create a boolean flag and put a critical section around every access. This works just as well, but is error prone (one access without a critical section breaks the entire system). The Event solution doesn't have that problem. If you use Sleep in any application, you can pretty much be assured that your design is flawed. Using it in Multithreaded applications to try to manage synchronization between threads is worse than useless. Use proper thread synchronization techniques and you won't have issues. If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

          J 1 Reply Last reply
          0
          • Z Zac Howland

            Create an event handle (using CreateEvent). Pass that handle to the loop when you create it (its quite common to pass such objects in the LPARAM pointer used when creating a thread). When you need to terminate the thread, call SetEvent. Internally to the loop, you will use WaitForSingleObject with an appropriate timeout value (in your case, 0 would probably work since you just want to check to make sure it has already been set). If WaitForSingleObject returns WAIT_OBJECT_0, then your event was signaled and you should stop the loop. Alternatively, you could create a boolean flag and put a critical section around every access. This works just as well, but is error prone (one access without a critical section breaks the entire system). The Event solution doesn't have that problem. If you use Sleep in any application, you can pretty much be assured that your design is flawed. Using it in Multithreaded applications to try to manage synchronization between threads is worse than useless. Use proper thread synchronization techniques and you won't have issues. If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

            J Offline
            J Offline
            James R Twine
            wrote on last edited by
            #6

            Zac Howland wrote:

            Alternatively, you could create a boolean flag and put a critical section around every access. This works just as well, but is error prone (one access without a critical section breaks the entire system). The Event solution doesn't have that problem.

            You can also go the shared variable route and use things like InterlockedCompareExchange(...) (CMPXCHG) as well.  One thing though - for this particular kind of situation, I am not sure that synchronized access is required.  Since the value is not being used as a counter, or anything like that but just a simple flag, it should be OK to have one thread reading it waiting for its value to change while another threads writes it (once) to set that value.  I do not think that the reading of the value will interfere with the writing of it, and the thread would catch the change on the next read.  (Assuming automatic volatile handling and things like that.)    And yes, that was my 5.    Peace! -=- James


            If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
            Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
            DeleteFXPFiles & CheckFavorites (Please rate this post!)

            1 Reply Last reply
            0
            • A anilksingh

              IN a Dialog I have two CButton when i clicked on first button a loop starts. The requirement is when i click on second button it should break the loop. How i can communicate this to the loop. I tried Sleep so that i can check the status of common variable. But this variable is updatted only when the loop terminates. What will be the possible solution of my Problem.

              E Offline
              E Offline
              Eytukan
              wrote on last edited by
              #7

              As your thread title says, you should go for multithreading rather than the sleeping business. But what's the nature of the loop? can it be done with a Timer? I used to create threads unnecessarily when it could be done with timers :sigh:. So see to that it cannot be done with a timer first then go for multithreading. As said by David, never get your Sleep inside your thread or any loop, it puts the entire application to sleep :zzz:


              --[:jig:]-- [My Current Status]

              J 1 Reply Last reply
              0
              • _ _AnsHUMAN_

                one thing that you can do is that create a static flag=false as a global variable. now in the loop you can check that if the flag is set to true. (You will set the flag to true when the second button is pressed.) if the flag is set simply put return 0; in the block of code where you want the thread function to end. Here's some code for you that is inside the thread function :

                // Code inside the thread function and m_number is the 
                //variable for the edit box whose number property is set to true
                CMyDlg *test=(CMyDlg *)pVoid;
                	for(int i=0;i<1000;i++)
                	{
                		Sleep(10);
                		if(flag==true)
                		{
                			CString s;
                			s.Format ("%d",i);
                			AfxMessageBox("Thread stoping on "+ s);
                			return 0;
                		}
                		else
                		{
                			CString s;
                			s.Format ("%d",i);
                			test->m_number.SetWindowText (s);
                		}
                	}
                	return 0;
                

                Somethings seem HARD to do, until we know how to do them. ;-) _AnShUmAn_ -- modified at 9:34 Tuesday 13th June, 2006

                S Offline
                S Offline
                sunit5
                wrote on last edited by
                #8

                put the shared resource in crtical section (global varaible)dont use sleep never say die

                _ 1 Reply Last reply
                0
                • E Eytukan

                  As your thread title says, you should go for multithreading rather than the sleeping business. But what's the nature of the loop? can it be done with a Timer? I used to create threads unnecessarily when it could be done with timers :sigh:. So see to that it cannot be done with a timer first then go for multithreading. As said by David, never get your Sleep inside your thread or any loop, it puts the entire application to sleep :zzz:


                  --[:jig:]-- [My Current Status]

                  J Offline
                  J Offline
                  James R Twine
                  wrote on last edited by
                  #9

                  (Assuming you are talking about Sleep(...)...)

                  VuNic wrote:

                  As said by David, never get your Sleep inside your thread or any loop, it puts the entire application to sleep

                  No, it just the thread it is called on...  An application may consist of multiple threads.  Sleep(...) only affects one particular thread.    Peace! -=- James


                  If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
                  Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
                  DeleteFXPFiles & CheckFavorites (Please rate this post!)

                  E 1 Reply Last reply
                  0
                  • S sunit5

                    put the shared resource in crtical section (global varaible)dont use sleep never say die

                    _ Offline
                    _ Offline
                    _AnsHUMAN_
                    wrote on last edited by
                    #10

                    It was just to show the user. Afterall this was not a live example. It was just to give the user the time to perform the inputs while the thread is running Somethings seem HARD to do, until we know how to do them. ;-) _AnShUmAn_

                    1 Reply Last reply
                    0
                    • J James R Twine

                      (Assuming you are talking about Sleep(...)...)

                      VuNic wrote:

                      As said by David, never get your Sleep inside your thread or any loop, it puts the entire application to sleep

                      No, it just the thread it is called on...  An application may consist of multiple threads.  Sleep(...) only affects one particular thread.    Peace! -=- James


                      If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
                      Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
                      DeleteFXPFiles & CheckFavorites (Please rate this post!)

                      E Offline
                      E Offline
                      Eytukan
                      wrote on last edited by
                      #11

                      Thanks james, I thought Sleep is global call. hmm.. thanks for the info.. nice update for me.


                      --[:jig:]-- [My Current Status]

                      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