NSThread Cancel

Discussion in 'Mac Programming' started by McBgnr, Nov 24, 2009.

  1. McBgnr macrumors regular

    Joined:
    Apr 13, 2009
    #1
    Hi,

    I am NSThread in my application for some background task. I have a button thru which the thread can be cancelled in 10.5. However, 10.4 does not have cancel method, so I was wondering how to implement the functionality to stop the thread midway for it. Any ideas?
     
  2. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #2
    Have a BOOL protected by a lock (or, equivalently, an atomic BOOL property) that you check periodically from the background thread and set from the foreground thread when you need to cancel.
     
  3. darkwing macrumors 65816

    Joined:
    Jan 6, 2004
    #3
    Remember that you can't just say "thread go away" and have that happen safely. While POSIX allows for asynchronous cancels, it's regarded as a bad idea. The thread needs to clean up resources it's using in order to avoid memory leaks and certain forms of contention. Catfish has the best advice for you in this case, imho.
     
  4. Eraserhead macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #4
    Aren't BOOL's atomic by default?
     
  5. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #5
    Hmm... you'd need to declare it volatile if you want to not use a lock. Otherwise the compiler is free to hoist the check out of the loop. i.e. convert this:

    Code:
    while(!cancelled) {}
    
    into

    Code:
    if (!cancelled) {
        while(1) {}
    }
    
     

Share This Page