• 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: Messages between Threads
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Messages between Threads


  • Subject: Re: Messages between Threads
  • From: Michael Vannorsdel <email@hidden>
  • Date: Mon, 16 Mar 2009 08:09:31 -0600

You'll need to use an atomic operation to access tempSum in the main thread as well and make sure tempSum is on a 4 byte boundary (required by atomic ops).

But a cleaner method would be to keep a local running total in the worker thread and after your time period send a message to the main thread with the worker total as an NSNumber for the object for performSelectorOnMainThread... Then the main thread adds this value to the full total. The basic idea would look like:


//Worker thread
- (void)add2Number: (int)i
{
static int localSum = 0; //Don't use static if you're running this same method from multiple threads.
//But from a single worker it's ok and convenient


	localSum += i;

if ( more than 0.1 seconds have passed )
{
[ self performSelectorOnMainThread:@selector(addToSum:) withObject: [NSNumber numberWithInt:localSum] waitUntilDone:NO];


		localSum  = 0;  //reset local sum for next round
	}
}


//Main thread - (void)addToSum:(NSNumber*)num { sumTotal += [num intValue];

	self.sum = sumTotal;
}

This avoids the complexities of managing atomic reads/writes.

On Mar 15, 2009, at 11:43 PM, Gerriet M. Denkmann wrote:

Could you please point to the exact section where it is stated that it is not OK to update a bound property from a background thread?


If main is an instance of the Main class, which has:

- (void)add2Number: (int)i
{
	OSAtomicAdd32 (i, &tempSum);

if ( more than 0.1 seconds have passed )
[ self performSelectorOnMainThread:@selector(reallySum) withObject:nil waitUntilDone:NO];
}


- (void)reallySum
{
	self.sum = tempSum;
}

The property "sum" is bound to the "value" of some NSTextField.

Is is ok to send [ main add2Number: someNumber ] from another thread?

_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


References: 
 >Re: Messages between Threads (From: "Gerriet M. Denkmann" <email@hidden>)

  • Prev by Date: Re: case-insensitive NSDictionary
  • Next by Date: Re: Type Declaration With Protocol
  • Previous by thread: Re: Messages between Threads
  • Next by thread: Re: Messages between Threads
  • Index(es):
    • Date
    • Thread