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. .NET (Core and Framework)
  4. Safe thread termination in unmanaged code

Safe thread termination in unmanaged code

Scheduled Pinned Locked Moved .NET (Core and Framework)
7 Posts 3 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 Offline
    S Offline
    supercat9
    wrote on last edited by
    #1

    If I have a quantity of unmanaged code (in C, designed for another system), and most of it could be safely terminated at any time but it makes callbacks into managed code which could not be so terminated, would it be safe to do something like:

    /* In the unmanaged section */
    volatile int statflag;
    /* Zero when running C code that may be terminated.
    One when running code that must not be terminated.
    Two when termination has been requested */

    if (Exchange(&statflag, 1) == 0)
    {
    call_managed_code();
    if (Exchange(&statflag, 0) != 1))
    terminate();
    }
    else
    terminate();

    ' In the other thread...
    If Threading.Interlocked.Exchange(safeflag, 2) = 0 Then
    TheThread.Terminate

    If the portion of the code which is in C never does anything that could not be safely stopped asynchronously while safeflag is one, would there be any danger in calling Terminate() upon such a thread? Obviously any resources that had been allocated by that thread would have to be freed elsewhere, but in this particular application I'm not expecting the unmanaged code to use only resources that are given to it by other code (which could then take care of any necessary de-allocation). In the particular application, there is a risk that the C portion of the code could hang without any callbacks to the managed portion, so I'd like to be able to use something more "potent" than Thread.Interrupt; is Thread.Terminate safe if used only upon a thread which is known not to hold any locks or be manipulating any other dangerous constructs?

    L 1 Reply Last reply
    0
    • S supercat9

      If I have a quantity of unmanaged code (in C, designed for another system), and most of it could be safely terminated at any time but it makes callbacks into managed code which could not be so terminated, would it be safe to do something like:

      /* In the unmanaged section */
      volatile int statflag;
      /* Zero when running C code that may be terminated.
      One when running code that must not be terminated.
      Two when termination has been requested */

      if (Exchange(&statflag, 1) == 0)
      {
      call_managed_code();
      if (Exchange(&statflag, 0) != 1))
      terminate();
      }
      else
      terminate();

      ' In the other thread...
      If Threading.Interlocked.Exchange(safeflag, 2) = 0 Then
      TheThread.Terminate

      If the portion of the code which is in C never does anything that could not be safely stopped asynchronously while safeflag is one, would there be any danger in calling Terminate() upon such a thread? Obviously any resources that had been allocated by that thread would have to be freed elsewhere, but in this particular application I'm not expecting the unmanaged code to use only resources that are given to it by other code (which could then take care of any necessary de-allocation). In the particular application, there is a risk that the C portion of the code could hang without any callbacks to the managed portion, so I'd like to be able to use something more "potent" than Thread.Interrupt; is Thread.Terminate safe if used only upon a thread which is known not to hold any locks or be manipulating any other dangerous constructs?

      L Offline
      L Offline
      led mike
      wrote on last edited by
      #2

      supercat9 wrote:

      would there be any danger in calling Terminate() upon such a thread?

      Hi again, welcome to CodeProject. Let me just warn you that many of the regular members here will tend to flame on people who are obviously not reading the documentation. TerminateThread[^]

      TerminateThread is a dangerous function that should only be used in the most extreme cases.

      Terminating threads is never considered Best Practice. On the other hand if you have no other choice then it really doesn't matter what dangers might exist. Obviously, if you do have another choice then go with the other choice.

      S 1 Reply Last reply
      0
      • L led mike

        supercat9 wrote:

        would there be any danger in calling Terminate() upon such a thread?

        Hi again, welcome to CodeProject. Let me just warn you that many of the regular members here will tend to flame on people who are obviously not reading the documentation. TerminateThread[^]

        TerminateThread is a dangerous function that should only be used in the most extreme cases.

        Terminating threads is never considered Best Practice. On the other hand if you have no other choice then it really doesn't matter what dangers might exist. Obviously, if you do have another choice then go with the other choice.

        S Offline
        S Offline
        supercat9
        wrote on last edited by
        #3

        Hi again, welcome to CodeProject. Let me just warn you that many of the regular members here will tend to flame on people who are obviously not reading the documentation. It states that it is a dangerous function that should only be used in extreme cases. I can certainly appreciate that many bad things can happen if it is done on managed code or code which uses the Windows API. My situation is a bit different from the usual one, though, and I was wondering whether anyone had done anything similar. I'm writing code for a microcontroller with a few kbytes of RAM and a few dozen kbytes of code. For testing purposes, I would like to be able to run the code on a Windows machine, replacing the physical I/O routines with calls to wrapper functions which would call back into managed code that would simulate the I/O in question. If every call to a wrapper function checks for a "terminate, please" flag, then any loop which calls any of the wrapper functions will exit once the flag in question is set, but there's no guarantee of when that will actually take place. If something goes wrong in the target system code, such callbacks might never take place. Since the target application shouldn't get stuck in such a loop, it probably wouldn't be the end of the world to require that someone use ctrl-alt-del and kill the non-responsive application, but that would seem more dangerous than having the application terminate the stuck thread, especially since the application might be doing things on other threads that should not be blindly terminated.

        L 1 Reply Last reply
        0
        • S supercat9

          Hi again, welcome to CodeProject. Let me just warn you that many of the regular members here will tend to flame on people who are obviously not reading the documentation. It states that it is a dangerous function that should only be used in extreme cases. I can certainly appreciate that many bad things can happen if it is done on managed code or code which uses the Windows API. My situation is a bit different from the usual one, though, and I was wondering whether anyone had done anything similar. I'm writing code for a microcontroller with a few kbytes of RAM and a few dozen kbytes of code. For testing purposes, I would like to be able to run the code on a Windows machine, replacing the physical I/O routines with calls to wrapper functions which would call back into managed code that would simulate the I/O in question. If every call to a wrapper function checks for a "terminate, please" flag, then any loop which calls any of the wrapper functions will exit once the flag in question is set, but there's no guarantee of when that will actually take place. If something goes wrong in the target system code, such callbacks might never take place. Since the target application shouldn't get stuck in such a loop, it probably wouldn't be the end of the world to require that someone use ctrl-alt-del and kill the non-responsive application, but that would seem more dangerous than having the application terminate the stuck thread, especially since the application might be doing things on other threads that should not be blindly terminated.

          L Offline
          L Offline
          led mike
          wrote on last edited by
          #4

          supercat9 wrote:

          For testing purposes

          For testing I would think as long as you can accomplish the testing goals you wouldn't care about the dangers. I imagine the author talking about dangers is addressing production software environments.

          S 1 Reply Last reply
          0
          • L led mike

            supercat9 wrote:

            For testing purposes

            For testing I would think as long as you can accomplish the testing goals you wouldn't care about the dangers. I imagine the author talking about dangers is addressing production software environments.

            S Offline
            S Offline
            supercat9
            wrote on last edited by
            #5

            I imagine the author talking about dangers is addressing production software environments. The system might get used in something between a testing and production environment; the actual hardware device includes the ability to initiate TCP connections to a server, and it's possible that customers might use the "simulator" to simulate having a number of devices connecting to the server at once. By the time the code gets to the customer it shouldn't get into bad situations, but in case something bad happens (e.g. the server comes back with a response that would confuse the device) it would be nicer to allow a controlled shutdown of the thread than to force the user to kill the application. I guess my main question should perhaps have been better phrased as, "The documentation says to avoid using TerminateThread; is there any accepted style for wrapping it in those circumstances where its use may be reasonably safe and appropriate?" I guess if there's no way to recover the stack in older versions of Windows that would be bad, but it could still be better than having a stuck thread gobble up all the CPU time it can get. On a related note, under what circumstances is an "isBackground" thread killed off blindly when an application terminates? If a thread is doing a "WriteAllText" to create and write a file, is the function guaranteed to either fail altogether or succeed completely in case of application termination, or should it be surrounded by saving the isBackground property of the current thread, setting it to False, performing the function, and restoring the old value of isBackground? In any case, thanks for responding. -- John

            L L 2 Replies Last reply
            0
            • S supercat9

              I imagine the author talking about dangers is addressing production software environments. The system might get used in something between a testing and production environment; the actual hardware device includes the ability to initiate TCP connections to a server, and it's possible that customers might use the "simulator" to simulate having a number of devices connecting to the server at once. By the time the code gets to the customer it shouldn't get into bad situations, but in case something bad happens (e.g. the server comes back with a response that would confuse the device) it would be nicer to allow a controlled shutdown of the thread than to force the user to kill the application. I guess my main question should perhaps have been better phrased as, "The documentation says to avoid using TerminateThread; is there any accepted style for wrapping it in those circumstances where its use may be reasonably safe and appropriate?" I guess if there's no way to recover the stack in older versions of Windows that would be bad, but it could still be better than having a stuck thread gobble up all the CPU time it can get. On a related note, under what circumstances is an "isBackground" thread killed off blindly when an application terminates? If a thread is doing a "WriteAllText" to create and write a file, is the function guaranteed to either fail altogether or succeed completely in case of application termination, or should it be surrounded by saving the isBackground property of the current thread, setting it to False, performing the function, and restoring the old value of isBackground? In any case, thanks for responding. -- John

              L Offline
              L Offline
              Luc 648011
              wrote on last edited by
              #6

              supercat9 wrote:

              under what circumstances is an "isBackground" thread killed off blindly

              AFAIK it always is. Therefore it is a bad idea to use a background thread for writing files and databases. :)

              1 Reply Last reply
              0
              • S supercat9

                I imagine the author talking about dangers is addressing production software environments. The system might get used in something between a testing and production environment; the actual hardware device includes the ability to initiate TCP connections to a server, and it's possible that customers might use the "simulator" to simulate having a number of devices connecting to the server at once. By the time the code gets to the customer it shouldn't get into bad situations, but in case something bad happens (e.g. the server comes back with a response that would confuse the device) it would be nicer to allow a controlled shutdown of the thread than to force the user to kill the application. I guess my main question should perhaps have been better phrased as, "The documentation says to avoid using TerminateThread; is there any accepted style for wrapping it in those circumstances where its use may be reasonably safe and appropriate?" I guess if there's no way to recover the stack in older versions of Windows that would be bad, but it could still be better than having a stuck thread gobble up all the CPU time it can get. On a related note, under what circumstances is an "isBackground" thread killed off blindly when an application terminates? If a thread is doing a "WriteAllText" to create and write a file, is the function guaranteed to either fail altogether or succeed completely in case of application termination, or should it be surrounded by saving the isBackground property of the current thread, setting it to False, performing the function, and restoring the old value of isBackground? In any case, thanks for responding. -- John

                L Offline
                L Offline
                led mike
                wrote on last edited by
                #7

                supercat9 wrote:

                "The documentation says to avoid using TerminateThread;

                Well I thought I already covered this but let's have another go.

                led mike wrote:

                Terminating threads is never considered Best Practice. On the other hand if you have no other choice then it really doesn't matter what dangers might exist. Obviously, if you do have another choice then go with the other choice.

                What it comes down to is if you can accomplish what is needed without terminating threads (stop the thread gracefully), do it that way, always, period. However if for some reason terminating threads is all you can do and you must do it, then it doesn't matter if there are dangers does it? Now to me that seems like a pretty simple concept. However you seem to be thinking along another line that I have so far failed to understand.

                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