• 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: Threads, messages and blocking
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Threads, messages and blocking


  • Subject: Re: Threads, messages and blocking
  • From: Chris Hanson <email@hidden>
  • Date: Fri, 30 May 2003 09:28:24 -0400

On Thursday, May 29, 2003, at 06:26 PM, Sean Harding wrote:
only allows communication thread 2->thread 1
(main thread), it appears. So it doesn't give me any way to have the main
thread send thread 2 another "go to work" message. Am I misunderstanding the
suggestion?

One way to do this is to have a shared command variable or queue that's protected by a condition lock.

The condition lock is used to signal from thread 1 to thread 2 when there's more work available. You create it in thread 1 with condition 0. When thread 1 wants to communicate data via a shared variable to thread 2, it locks the lock when its condition is 0, changes the variable, and then unlocks the lock with condition 1.

At the top of thread 2's work loop, it locks the lock when its condition is 1, reads the change to the variable, and then unlocks the lock with condition 0. Then it does whatever it needs to do with the change to the variable. (Note: It does this after unlocking, not before! Otherwise you'll block thread 1 longer than necessary.)

// In thread 1
[lock lockWhenCondition:0];
[messageQueue addObject:message];
[lock unlockWithCondition:1];
// go on here

// In thread 2:
[lock lockWhenCondition:1];
message = [messageQueue lastObject];
[messageQueue removeLastObject];
[lock unlockWithCondition:0];
// process the message here

To get the best performance, your critical sections (between lock & unlock) should always be as small as possible. This is true in general for threaded code: Minimize dependencies.

-- Chris

--
Chris Hanson, bDistributed.com, Inc. | Email: email@hidden
Custom Application Development | Phone: +1-847-372-3955
http://bdistributed.com/ | Fax: +1-847-589-3738
http://bdistributed.com/Articles/ | Personal Email: email@hidden
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

References: 
 >Re: Threads, messages and blocking (From: Sean Harding <email@hidden>)

  • Prev by Date: Re: Carbon : start-up volume name/path as POSIX
  • Next by Date: Re: Unit test tool
  • Previous by thread: Re: Threads, messages and blocking
  • Next by thread: NSScreen and NSCoptBits
  • Index(es):
    • Date
    • Thread