4. • Concurrency is about dealing with lots of
things at once.Parallelism is about doing lots
of things at once.
• Not the same, but related.
• One is about structure, one is about
execution.
• Concurrency provides a way to structure a
solution to solve a problem that may (but not
necessarily) be parallelizable.
13年1月17⽇日星期四
5. • Concurrency is about dealing with lots of
things at once.Parallelism is about doing lots
of things at once.
• Not the same, but related.
• One is about structure, one is about
execution.
• Concurrency provides a way to structure a
solution to solve a problem that may (but not
necessarily) be parallelizable.
Concurrency is not Parallelism
13年1月17⽇日星期四
46. Mutex
BOOL moreToDo = YES;
NSLock *theLock = [[NSLock alloc] init];
...
while (moreToDo) {
/* Do another increment of calculation */
/* until there’s no more to do. */
if ([theLock tryLock]) {
/* Update display used by all threads. */
[theLock unlock];
}
}
13年1月17⽇日星期四
48. NSConditionLock
producer.m thread:
id condLock = [[NSConditionLock alloc] initWithCondition:NO_DATA];
while(YES)
{
[condLock lock];
/* Add data to the queue. */
[condLock unlockWithCondition:HAS_DATA];
}
consumer thread:
while (YES)
{
[condLock lockWhenCondition:HAS_DATA];
/* Remove data from the queue. */
[condLock unlockWithCondition:(isEmpty ? NO_DATA : HAS_DATA)];
// Process the data locally.
}
13年1月17⽇日星期四
56. CAS
int compare_and_swap (int* reg, int oldval, int newval)
{
int old_reg_val = *reg;
if (old_reg_val == oldval)
*reg = newval;
return old_reg_val;
}
13年1月17⽇日星期四
68. ⽣生命周期
Run Loop
A run loop is an event processing loop that you use to
schedule work and coordinate the receipt of incoming
events.
13年1月17⽇日星期四
69. ⽣生命周期
Run Loop
A run loop is an event processing loop that you use to
schedule work and coordinate the receipt of incoming
events.
The purpose of a run loop is to keep your thread busy
when there is work to do and put your thread to sleep
when there is none.
13年1月17⽇日星期四
70. - (void)skeletonThreadMain
{
// Set up an autorelease pool here if not using garbage collection.
BOOL done = NO;
// Add your sources or timers to the run loop and do any other setup.
do
{
// Start the run loop but return after each source is handled.
SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, YES);
// If a source explicitly stopped the run loop, or if there are no
// sources or timers, go ahead and exit.
if((result == kCFRunLoopRunStopped) || (result ==
kCFRunLoopRunFinished))
done = YES;
// Check for any other exit conditions here and set the
// done variable as needed.
}
while (!done);
// Clean up code here. Be sure to release any allocated autorelease pools.
}
13年1月17⽇日星期四