マルチスレッド足かせ

20922 ワード

1、  :

1.1 iOS           ,   :



1.、NSThread 



2、Cocoa NSOperation (iOS      NSOperation NSOperationQueue   )



3、GCD    :Grand Central Dispatch( iOS      Grand Central Dispatch(GCD)     )



           ,           ,           ,  Apple      。



           NSThread,     2、31.2           :



NSThread:



  :NSThread         



  :             ,    。                   



NSThread          :



Technology

    



Description



Cocoa threads

    



Cocoa implements threads using the NSThread class. Cocoa also provides methods on NSObject for spawning new threads and executing code on already-running threads. For more information, see “Using NSThread” and “Using NSObject to Spawn a Thread.”



POSIX threads

    



POSIX threads provide a C-based interface for creating threads. If you are not writing a Cocoa application, this is the best choice for creating threads. The POSIX interface is relatively simple to use and offers ample flexibility for configuring your threads. For more information, see “Using POSIX Threads”



Multiprocessing Services

    



Multiprocessing Services is a legacy C-based interface used by applications transitioning from older versions of Mac OS. This technology is available in OS X only and should be avoided for any new development. Instead, you should use the NSThread class or POSIX threads. If you need more information on this technology, see Multiprocessing Services Programming Guide.

    cocoa thread   。





Cocoa operation 



  :         ,       ,                 。



Cocoa operation       NSOperation ,NSOperationQueue。NSOperation     ,          ,                  :NSInvocationOperation   NSBlockOperation。  NSOperation     ,      NSOperationQueue     。



GCD



Grand Central Dispatch (GCD) Apple              。 iOS4.0        。GCD       NSThread, NSOperationQueue, NSInvocationOperation             。   iOS      6 ,             。





             ,       NSThread   。

2、NSThread   

2.1 NSThread          :



- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument



+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument



        ,       



[cpp] view plaincopy



    1、[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];  

    2、NSThread* myThread = [[NSThread alloc] initWithTarget:self  

                                            selector:@selector(doSomething:)  

                                            object:nil];  

    [myThread start];  



2.2     :



selector :       ,  selector       ,        。



target  :selector       



argument:   target     ,    nil



                    ,             ,         ,                       

2.3 PS:          :



 NSObject      performSelectorInBackground:withObject:       :

[Obj performSelectorInBackground:@selector(doSomething) withObject:nil];

2.42.4.1    singeView app



    ,  xib       imageView  。  control   viewControll



er.h     imageView IBOutlet 



ViewController.m   :

[cpp] view plaincopy



    //  

    //  ViewController.m  

    //  NSThreadDemo  

    //  

    //  Created by rongfzh on 12-9-23.  

    //  Copyright (c) 2012  rongfzh. All rights reserved.  

    //  

      

    #import "ViewController.h"  

    #define kURL @"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"  

    @interface ViewController ()  

      

    @end  

      

    @implementation ViewController  

      

    -(void)downloadImage:(NSString *) url{  

        NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];  

        UIImage *image = [[UIImage alloc]initWithData:data];  

        if(image == nil){  

              

        }else{  

            [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];  

        }  

    }  

      

    -(void)updateUI:(UIImage*) image{  

        self.imageView.image = image;  

    }  

      

      

    - (void)viewDidLoad  

    {  

        [super viewDidLoad];  

          

    //    [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:kURL];  

        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage:) object:kURL];  

        [thread start];  

    }  

      

    - (void)didReceiveMemoryWarning  

    {  

        [super didReceiveMemoryWarning];  

        // Dispose of any resources that can be recreated.  

    }  

      

    @end  



2.4.2     



                    ?



[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];

performSelectorOnMainThread NSObject   ,             ,            :



 :performSelector:onThread:withObject:waitUntilDone: 

      :





       。

2.3     



                NSThread     :



.h



[cpp] view plaincopy



    #import <UIKit/UIKit.h>  

      

    @class ViewController;  

      

    @interface AppDelegate : UIResponder <UIApplicationDelegate>  

    {  

        int tickets;  

        int count;  

        NSThread* ticketsThreadone;  

        NSThread* ticketsThreadtwo;  

        NSCondition* ticketsCondition;  

        NSLock *theLock;  

    }  

    @property (strong, nonatomic) UIWindow *window;  

      

    @property (strong, nonatomic) ViewController *viewController;  

      

    @end  



[cpp] view plaincopy



    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  

    {  

          

        tickets = 100;  

        count = 0;  

        theLock = [[NSLock alloc] init];  

        //      

        ticketsCondition = [[NSCondition alloc] init];  

        ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  

        [ticketsThreadone setName:@"Thread-1"];  

        [ticketsThreadone start];  

          

          

        ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  

        [ticketsThreadtwo setName:@"Thread-2"];  

        [ticketsThreadtwo start];  

          

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

        // Override point for customization after application launch.  

        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];  

        self.window.rootViewController = self.viewController;  

        [self.window makeKeyAndVisible];  

        return YES;  

    }  

      

    - (void)run{  

        while (TRUE) {  

            //     

    //        [ticketsCondition lock];  

            [theLock lock];  

            if(tickets >= 0){  

                [NSThread sleepForTimeInterval:0.09];  

                count = 100 - tickets;  

                NSLog(@"     :%d,  :%d,   :%@",tickets,count,[[NSThread currentThread] name]);  

                tickets--;  

            }else{  

                break;  

            }  

            [theLock unlock];  

    //        [ticketsCondition unlock];  

        }  

    }  



         lock,      -1.  lock               。

           ,  NSCondition ,   :NSLock。 NSCondition      。



       



       



        [ticketsCondition signal];        ,                。



  :



[cpp] view plaincopy



    #import "AppDelegate.h"  

      

    #import "ViewController.h"  

      

    @implementation AppDelegate  

      

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  

    {  

          

        tickets = 100;  

        count = 0;  

        theLock = [[NSLock alloc] init];  

        //      

        ticketsCondition = [[NSCondition alloc] init];  

        ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  

        [ticketsThreadone setName:@"Thread-1"];  

        [ticketsThreadone start];  

          

        ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  

        [ticketsThreadtwo setName:@"Thread-2"];  

        [ticketsThreadtwo start];  

          

        NSThread *ticketsThreadthree = [[NSThread alloc] initWithTarget:self selector:@selector(run3) object:nil];  

        [ticketsThreadthree setName:@"Thread-3"];  

        [ticketsThreadthree start];      

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

        // Override point for customization after application launch.  

        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];  

        self.window.rootViewController = self.viewController;  

        [self.window makeKeyAndVisible];  

        return YES;  

    }  

      

    -(void)run3{  

        while (YES) {  

            [ticketsCondition lock];  

            [NSThread sleepForTimeInterval:3];  

            [ticketsCondition signal];  

            [ticketsCondition unlock];  

        }  

    }  

      

    - (void)run{  

        while (TRUE) {  

            //     

            [ticketsCondition lock];  

            [ticketsCondition wait];  

            [theLock lock];  

            if(tickets >= 0){  

                [NSThread sleepForTimeInterval:0.09];  

                count = 100 - tickets;  

                NSLog(@"     :%d,  :%d,   :%@",tickets,count,[[NSThread currentThread] name]);  

                tickets--;  

            }else{  

                break;  

            }  

            [theLock unlock];  

            [ticketsCondition unlock];  

        }  

    }  



wait   ,        3             wait



    



         @synchronized     NSLock   ,             NSLock,         。

- (void)doSomeThing:(id)anObj

{

    @synchronized(anObj)

    {

        // Everything between the braces is protected by the @synchronized directive.

    }

}

          ,  :   NSRecursiveLock,   NSConditionLock,    NSDistributedLock  ,           



NSThread         :http://download.csdn.net/detail/totogo2010/4591149



     :   http://blog.csdn.net/totogo2010/  ,      。       ,               ,  !