《iOS5 programming cookbook》学习笔记5 Concurrency

本文介绍了iOS开发中GCD的基础知识,包括传统的多线程实现方式和GCD的简洁优势。GCD提供了Main Queue、Concurrent Queues和Serial Queues三种类型。通过GCD,开发者只需关注代码块,而无需手动管理线程。文中还讨论了块对象和GCD的重要性,以及如何使用GCD进行任务调度和更新UI。
摘要由CSDN通过智能技术生成

有必要了解一下,说来惭愧,从来就没系统学过某一个平台的多线程,ios上把自己的第一次奉献出去了。

简单介绍了一下什么是GCD

然后有个对比,

Traditionally, programmers had to create their own threads to perform tasks in parallel.For instance, an iOS developer would create a thread similar to this to perform anoperation 1000 times: 

  • -  (void) doCalculation{
    /* Do your calculation here */

    }

  • -  (void) calculationThreadEntry{

    @autoreleasepool {NSUInteger counter = 0;

    while ([[NSThread currentThread] isCancelled] == NO){[self doCalculation];

    counter++;
    if (counter >= 1000){

    break;}

    }}

    }

  • -  (BOOL) application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    /* Start the thread */
    [NSThread detachNewThreadSelector:@selector(calculationThreadEntry)

    toTarget:selfwithObject:nil];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];[self.window makeKeyAndVisible];
    return YES;

    1. The programmer has to start the thread manually and then create the required structurefor the thread (entry point, autorelease pool, and thread’s main loop). When we writethe same code with GCD, we really won’t have to do much:

      dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

      size_t numberOfIterations = 1000;

      dispatch_async(queue, ^(void) {dispatch_apply(numberOfIterations, queue, ^(size_t iteration){

      /* Perform the operation here */

    page372image15368
    page372image15640

    });}); 

    高下立判,简单很多。


     three types of dispatch queues:

    Main Queue


    Concurrent Queues


    Serial Queues

    介绍了一下GCD存在的意义和目的:

     What’s so special about block objects and GCD, you mightask? It’s simple: no more threads! All you have to do is to put your code in block objectsand ask GCD to take care of the execution of that code for you. 


introduction 这么长,累啊。正好

  • Operation objects are key-value observing (KVO) compliant on various key pathssuch asisFinished, isReady,andisExecuting.We will be discussing Key Value Coding and Key Value Observing in a later chapter. 

正好这块儿不懂

run loop     这块儿也不懂。

Every thread and timer must beadded to a run loop. A run loop, as its name implies, is a loop during which differentevents can occur, such as a timer firing or a thread running.  

总算看完这个超长的介绍,后面这段有点看不大明白,状态不好啊。


5.1 

昨天已经看了一遍,今天又看了一遍,对比了一下三个例子,大概了然了。提到了几个术语例如 inline     应该是所谓的内联函数吧,以后再说。

5.2

先看了一下代码。大概明了,结果一看文章,一堆语法,可把我看晕了。

看不懂诶:

You don’t have to assign the nameselfto this parameter. You can sim-ply call this parameter anything else. However, if you call this parameterself,you can simply grab your block object’s code later and place it inan Objective-C method’s implementation without having to change ev-ery instance of your variable’s name toselffor it to be understood bythe compiler. 


看来还是

 use the getter and the setter methods of thissynthesized property 

比较万能一点。

这个很重要,要记住,比较容易出到面试题里面,我感觉,实干的话,一debug就知道结果了。

When it comes to inline block objects, there is oneveryimportant rule that you haveto remember: inline block objects copy the value for the variables in their lexical scope. 

贴上代码:

- (void) scopeTest{

  

  NSUInteger integerValue = 10;

  

  BlockWithNoParams myBlock = ^{

    NSLog(@"Integer value inside the block = %lu", 

          (unsigned long)integerValue);

  };

  

  integerValue = 20;

  

  /* Call the block here after changing the

   value of the integerValue variable */

  myBlock();

  

  NSLog(@"Integer value outside the block = %lu", 

        (unsigned long)integerValue);

  

}

结果和解释如下:

Integer value inside the block = 10Integer value outside the block = 20 

What’s happening here is that the block object is keeping a read-only copy of theintegerValuevariable for itself right where the block is implemented. You might bethinking: why is the block object capturing aread-onlyvalue of the local variableintegerValue?The answer is simple, and we’ve already learned it in this section. Unlessprefixed with storage type__block,local variables in the lexical scope of a block objectare just passed to the block object as read-only variables. Therefore, to change thisbehavior, we could change the implementation of ourscopeTestmethod to prefix theintegerValuevariable with__blockstorage type, like so:

- (void) scopeTest{
__block NSUInteger integerValue = 10;

/*************** Definition of internal block object ***************/

BlockWithNoParams myBlock = ^{

NSLog(@"Integer value inside the block = %lu",(unsigned long)integerValue);

};
/*************** End definition of internal block object ***************/

integerValue = 20;

/* Call the block here after changing the

value of the integerValue variable */myBlock();

NSLog(@"Integer value outside the block = %lu",(unsigned long)integerValue);

}
Now if we get the results from the console window after thescopeTestmethod is called,

we will see this:

Integer value inside the block = 20

Integer value outside the block = 20 

5.3  Invoking Block Objects

看完了

5.4 Dispatching  Tasks to Grand Central Dispatch

不是很明白

5.5

说明了一下,这个main queue 的重要性

This might not be that impressive. In fact, it is not impressive at all if you think aboutit. So what makes the main queue truly interesting? The answer is simple: when youare getting the maximum performance from GCD to do some heavy calculation onconcurrent or serial threads, you might want to display the results to your user or movea component on the screen. For that, youmustuse the main queue, because it is UI-related work. The functions shown in this section are theonlyway to get out of a serialor a concurrent queue while still utilizing GCD to update your UI, so you can imaginehow important it is. 


最后证明了一下,当前的线程,确实是主线程。

- (BOOL) application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

dispatch_queue_t mainQueue = dispatch_get_main_queue();

dispatch_async(mainQueue, ^(void) {

NSLog(@"Current thread = %@", [NSThread currentThread]);

NSLog(@"Main thread = %@", [NSThread mainThread]);});

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

self.window.backgroundColor = [UIColor whiteColor];[self.window makeKeyAndVisible];
return YES;


5.6 继续

代码看完了

5.7 over 觉得自己还是不大明白其中奥义,应该是没有实践的原因吧。

对queue 的概念,main global 等的概念不是很清楚,应该是看到后面了,前面的忘了,

5.8 over

多了个概念

double delayInSeconds = 2.0;

  dispatch_time_t delayInNanoSeconds =     dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);


5.9 开始 over 试了最后一个MySingleton.h 的例子没有成功。

5.10 over

5.11 over  

 start Constructing Your Own Dispatch Queues with GCD

1.这个identifier is a system wide identifier

2.making serial queues highly describele for construct FIFO tasks


5.12 start  完全没有接触过这个概念,(NSInvocationOperation),the main responsibility of an object of this type is to invoke a method in an object.

This is the most straightforward way to invoke a method inside an object using operations.

看不懂了,先暂停一下先。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值