• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Question about Threading
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Question about Threading


  • Subject: Re: Question about Threading
  • From: Chris Kane <email@hidden>
  • Date: Wed, 10 Aug 2005 13:23:45 -0700

On Aug 10, 2005, at 11:53 AM, Dominic Yu wrote:

2005/8/10, Chris Kane <email@hidden>:

Don't, however, try to solve the synchronization and "wait until the
background thread is done" by locking a lock in one thread which the
other thread unlocks.


wait... are you saying that using a BOOL and an NSLock is not OK? for example


- (void)someThread:(id)anObj {
  [aLock lock];
  while (aBool) {
    // do  stuff
  }
  [aLock unlock];
}

- (void)stopAboveThread:(id)sender {
  aBool = NO;
  [aLock lock];
  // do some other stuff
  [aLock unlock];
}

Is this incorrrect code?


No. In the code above, you're unlocking the lock in the same thread which locked it -- the locks and unlocks are paired.


This variation would be wrong:

- (void)startThread {
[aLock lock]; // lock the lock in the starter thread
[NSThread detach.... @selector(someThread:) ...]
}


- (void)someThread:(id)anObj {
while (aBool) {
// do stuff
}
[aLock unlock]; // unlocking the lock signals that this thread is done
}


- (void)stopAboveThread:(id)sender {
  aBool = NO;
  [aLock lock];    // wait until other thread is done
  [aLock unlock];
   // do stuff here
}


Here, aLock is locked by one thread in startThread, and unlocked by another in someThread:. This is an error in POSIX threads (pthreads), which NSLock and friends are based on (as well as the Carbon lock APIs). Implementations of pthreads may have variance with the spec (e.g., bugs), so I'd say at best you would be in implementation-defined territory, which might differ in different versions of the OS.


Chris Kane Cocoa Frameworks, Apple

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


References: 
 >Question about Threading (From: Michael Becker <email@hidden>)
 >Re: Question about Threading (From: Cameron Hayne <email@hidden>)
 >Re: Question about Threading (From: Chris Kane <email@hidden>)
 >Re: Question about Threading (From: Dominic Yu <email@hidden>)

  • Prev by Date: Re: Addressing Relationships in awakeFromInsert
  • Next by Date: WebServices problem
  • Previous by thread: Re: Question about Threading
  • Next by thread: Re: Question about Threading
  • Index(es):
    • Date
    • Thread