IOS Multithreading (GCD nsthread)

Source: Internet
Author: User

1.NSThread

①. Several ways of the thread

* First created, then started

Turn on thread    nsthread *thread =[[nsthread alloc]initwithtarget:self selector: @selector (run) Object:nil];    Start    [thread start];        Direct start    [nsthread detachnewthreadselector: @selector (< #selector #>) totarget:self Withobject:nil];

②. Other uses

    Gets the current thread    nsthread *current =[nsthread CurrentThread];        Get the main thread    + (nsthread*) mainthread;    Inter-thread communication (back to the main thread from the child threads)
-(void) performselectoronmainthread:<# (SEL) #> withobject:<# (ID) #> waituntildone:<# (BOOL) #>

CGD (Key)

1. Types of queues

* Concurrent queues: Multiple tasks can be performed concurrently

Get global Concurrent queue: Dispatch_get_global_queue (< #long Identifier#>, < #unsigned long flags#>)

* Serial queue: One task is completed before the next task is executed

A. Create yourself: dispatch_queue_create

B. Home row: Dispatch_get_main_queue

2. Method types for performing tasks

* Synchronization (Sync) Execution: Task can only be performed on the current thread

* Asynchronous (Async) Execution: Multiple threads can perform tasks (the system will automatically give you the open, you just write what you want to do)

3. Learn how to use queues in conjunction with

* Asynchronous Concurrent Queue

Gets the global concurrent queue    //The first parameter represents the priority    dispatch_queue_t queue= Dispatch_get_global_queue (dispatch_queue_priority_ DEFAULT, 0);    2. Add task to queue, perform task    dispatch_async (queue, ^{        NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Dispatch_async (queue, ^{             NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Dispatch_async (queue, ^{        NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Summary: 3 threads Open at the same time

* Asynchronous Serial Queue

  1. Create serial queue dispatch_queue_t queue=   dispatch_queue_create ("Com.itheima.queue", NULL);    Dispatch_async (queue, ^{        NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Dispatch_async (queue, ^{        NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Dispatch_async (queue, ^{        NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Summary: Only one thread will be opened;

* Synchronous serial

Create serial queue    dispatch_queue_t queue=dispatch_queue_create ("Wangbinbin.queue", NULL);    2. Add task to queue, perform task    dispatch_sync (queue, ^{        NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Dispatch_sync (queue, ^{                NSLog (@ "------Download picture 2-------%@", [Nsthread CurrentThread]);    });    Dispatch_sync (queue, ^{                NSLog (@ "------Download picture 3-------%@", [Nsthread CurrentThread]);    });        Summary: The thread will not be opened only on the current thread (the current thread is the main course, Dispatch_sync is the main path)

* Synchronizing concurrent queues

Gets the global concurrent queue    //The first parameter represents the priority    dispatch_queue_t Queue=dispatch_get_global_queue (dispatch_queue_priority_ DEFAULT, 0);        2. Add task to queue, perform task    dispatch_sync (queue, ^{                NSLog (@ "------Download picture 1-------%@", [Nsthread CurrentThread]);    });    Dispatch_sync (queue, ^{                NSLog (@ "------Download picture 2-------%@", [Nsthread CurrentThread]);    });    Dispatch_sync (queue, ^{        NSLog (@ "------Download picture 2-------%@", [Nsthread CurrentThread]);    });        Summary: New threads are not opened and concurrent queues lose concurrency

GCD Other common methods

1. From the child thread back to the main thread

NSLog (@ "%@", [Nsthread CurrentThread]);    Asynchronous concurrent Queue    Dispatch_async (dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{        NSLog (@ "------ %@ ", [Nsthread CurrentThread]);                Request Picture        Nsurl *url =[nsurl urlwithstring:@ "Http://img.taopic.com/uploads/allimg/110812/1820-110Q20K01549.jpg"] ;        NSData *data =[nsdata Datawithcontentsofurl:url];        UIImage *image=[uiimage Imagewithdata:data];         Back to the main thread display picture        Dispatch_async (Dispatch_get_main_queue (), ^{            NSLog (@ "+++%@", [Nsthread CurrentThread]);            (Self.imgview.image=image;        });            });

2. Disposable code

One-time code  Singleton used to get    static dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{                NSLog (@ "Execute only once,");    });

3. Delay operation

Delay operation 2 seconds    //calculation time    dispatch_time_t when=dispatch_time (Dispatch_time_now, (int64_t) (2.0 * nsec_per_sec));        Will execute the queue at the time of this point (queues can choose for themselves)    Dispatch_after (when, Dispatch_get_main_queue (), ^{                NSLog (@ "See Me!!!");    });

4. Queue groups

There is such a demand
First: Perform 2 time-consuming operations asynchronously, respectively
Second: Wait for 2 asynchronous operations to complete, then return to the main thread to perform the operation

Create a group of dispatch_group_t groups =dispatch_group_create ();    Open a task download image 1 __block UIImage *image1 =nil; Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{image1 =[self requestimagewithurl:@ "Http://d.hiphotos.baidu.com/image/pic/item/faedab64034f78f09c7428247d310a55b2191ced.jpg"    ];        });    Open a task download Image 2 __block UIImage *image2 =nil;  Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{image2 =[self requestimagewithurl:@ "http://b.hiphotos.baidu.com/image/h%3D360/sign=502eb6fad954564efa65e23f83df9cde/    80cb39dbb6fd5266c96cb6fdaf18972bd5073697.jpg "];    }); All the tasks in the group are executed, and the other operations Dispatch_group_notify (group, Dispatch_get_main_queue (), ^{self.        Uiimageview1.image=image1; Self.                Uiimageview2.image=image2;        Merge 2 Image Uigraphicsbeginimagecontextwithoptions (Cgsizemake (+), NO, 0); [Image1 Drawinrect:cgrectmakE (0, 0, 100, 100)];        [Image2 drawinrect:cgrectmake (100, 0, 100, 100)];        Self.biguiimageview.image=uigraphicsgetimagefromcurrentimagecontext ();    Close context Uigraphicsendimagecontext ();     });

IOS Multithreading (GCD nsthread)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.