IOS-multithreading GCD (original), ios-multithreading gcd original

Source: Internet
Author: User

IOS-multithreading GCD (original), ios-multithreading gcd original
Preface GCD

Grand Central DisPath NSOperation is a GCD-based encapsulation.

 

Basic knowledge

1. GCD advantages

(1) proposed solutions for multi-core parallel operations

(2) GCD will automatically take advantage of more CPU cores and dual-core quad-core

(3). GCD automatically manages the thread lifecycle (create Thread Scheduling task destruction thread)

(4) programmers only need to tell GCD what tasks they want to execute without writing any thread Management Code.

 

2. There are two core concepts in GCD

Task: What operations are performed

Queue: used to store tasks

 

3. There are two types of queues.

Serial Dispatch Queue: there is only one thread. Operations added to the Queue are executed in order of addition. After a task is executed, the next task can be executed.

Concurrent Dispatch Queue: there are multiple threads. After an operation is completed, the threads are arranged on the available processor, and advanced tasks are prioritized.

In fact, there is also a special queue in GCD, that is, there will always be only one thread in the main queue column-the main thread is used to execute the operation tasks of the main thread

 

4. Using GCD for multithreading can be abstracted into two steps

(1) locate the queue (main or serial or parallel Queue)

(2) synchronous or asynchronous execution of tasks in the queue

 

5. Two Methods for executing tasks in the queue

(1) Synchronization Can only execute tasks in the current thread and does not have the ability to enable new threads-the main thread

(2) asynchronous execution of tasks in new threads can enable new threads-subthreads

 

Next we will introduce the serial parallel synchronous asynchronous

-(Void) viewDidLoad {

[Super viewDidLoad];

Self. view. backgroundColor = [UIColor whiteColor];

// Do any additional setup after loading the view, typically from a nib.

# Pragma mark === serial synchronization ===

/// 1. Find the first parameter of the queue: name of the queue; second parameter: Specify the queue type

// Dispatch_queue_t serialQueue = dispatch_queue_create ("serialQueue", DISPATCH_QUEUE_SERIAL );

/// 2. Specify the first parameter for the task in the queue: In which queue the task runs the second parameter: The operation to be executed

/// Asyn is asynchronous. syn is synchronous.

// Dispatch_sync (serialQueue, ^ {

// NSLog (@ "1 ==%@", [NSThread currentThread]);

//});

//

# Pragma mark === Serial Asynchronous ===

// Dispatch_queue_t serialQueue = dispatch_queue_create ("serialQueue", DISPATCH_QUEUE_SERIAL );

// Dispatch_async (serialQueue, ^ {

// NSLog (@ "1 ==%@", [NSThread currentThread]);

//});

# Pragma mark === parallel synchronization ===

// Dispatch_queue_t concurrentQueue = dispatch_queue_create ("concurrentQueue", DISPATCH_QUEUE_CONCURRENT );

// Dispatch_sync (concurrentQueue, ^ {

// NSLog (@ "1 ==%@", [NSThread currentThread]);

//});

# Pragma mark === parallel asynchronous ===

Dispatch_queue_t concurrentQueue = dispatch_queue_create ("concurrentQueue", DISPATCH_QUEUE_CONCURRENT );

Dispatch_async (concurrentQueue, ^ {

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

});

}

Now let's create a new class. Let's take a look at the form of GCD to load the network image so that it will be displayed on self. view. Here I name it OneImageViewController and. m Code as follows:

# Import "OneImageViewController. h" # define kurl @ "http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601? Wid = 848 & hei = 848 & fmt = jpeg & qlt = 80 & op_sharpen = 0 & resMode = bicub & op_usm = 0.5, 0.5, 0, 0 & iccEmbed = 0 & layer = comp &. v = 1454777389943 "@ interface OneImageViewController () {UIImageView * imageView;} @ end @ implementation OneImageViewController-(void) viewDidLoad {[super viewDidLoad]; self. view. backgroundColor = [UIColor whiteColor];/* 1. create view 2. create a serial queue 3. execute tasks in the queue in asynchronous mode. 4. load network resources 5. return to the main thread to update the UI * // 1. create a view imageView = [[UIImageView alloc] initWithFrame: CGRectMake (50, 50,200,200)]; [self. view addSubview: imageView]; // 2. create a serial queue dispatch_queue_t serialQueue = dispatch_queue_create ("serialQueue", DISPATCH_QUEUE_SERIAL); // 3. execute the dispatch_async (serialQueue, ^ {// 4. load Network Resources NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: kurl]; UIImage * image = [UIImage imageWithData: data]; // 5. return to the main thread dispatch_get_main_queue. Find the main queue column dispatch_queue_t mainQueue = dispatch_get_main_queue (); dispatch_sync (mainQueue, ^ {// 6. update the UI imageView. image = image ;}) ;}@ end

  

I will name the class MoreImageViewViewController AND THE. m code for loading multiple network images using GCD as follows:

 

# Import "MoreImageViewViewController. h" # define kurl @ "http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601? Wid = 848 & hei = 848 & fmt = jpeg & qlt = 80 & op_sharpen = 0 & resMode = bicub & op_usm = 0.5, 0.5, 0, 0 & iccEmbed = 0 & layer = comp &. v = 1454777389943 "@ interface MoreImageViewViewController () {int imageIndex; dispatch_queue_t concurrentQueue;} @ end @ implementation moreimageviewcontroller-(void) viewDidLoad {[super viewDidLoad]; self. view. backgroundColor = [UIColor whiteColor]; self. edgesForExtendedLayout = UIRectEdgeNone;/* 1. create multiple views 2. find the parallel queue 3. specify multiple tasks for the parallel queue. load Network Resources in the sub-thread. return to main thread 6. updated UI */imageIndex = 100; // 1. create multiple views for (int row = 0; row <3; row ++) {for (int list = 0; list <2; list ++) {UIImageView * imageView = [[UIImageView alloc] initWithFrame: CGRectMake (10 + list * 200, 10 + row * 200,180,180)]; // imageView. backgroundColor = [UIColor orangeColor]; imageView. tag = imageIndex ++; [self. view addSubview: imageView] ;}// 2. find the parallel queue dispatch_get_global_queue and obtain the global parallel queue of the system. // The first parameter is the second parameter of priority. The reserved parameter is useless. // dispatch_queue_t concurrentQueue = dispatch_get_global_queue (0, 0 ); concurrentQueue = dispatch_queue_create ("concurrentQueue", DISPATCH_QUEUE_SERIAL); // 3. specify multiple tasks for this parallel Queue (int index = 0; index <6; index ++) {dispatch_async (concurrentQueue, ^ {[NSThread sleepForTimeInterval: 0.5]; // 4. load Network Resources NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: kurl]; UIImage * image = [UIImage imageWithData: data]; // 5. return to the main thread dispatch_sync (dispatch_get_main_queue (), ^ {// 6. update UI UIImageView * imageView = [self. view viewWithTag: 100 + index]; imageView. image = image;}) ;}) ;}[ self controlBtn] ;}- (void) controlBtn {UISegmentedControl * segment = [[UISegmentedControl alloc] initWithItems: @ [@ "pause", @ "enable",]; segment. frame = CGRectMake (50,620,300, 50); segment. apportionsSegmentWidthsByContent = YES; [self. view addSubview: segment]; [segment addTarget: self action: @ selector (clickSegment :) forControlEvents: UIControlEventValueChanged];}-(void) clickSegment :( UISegmentedControl *) sender {switch (sender. selectedSegmentIndex) {case 0: {// suspend the queue dispatch_suspend (concurrentQueue);} break; case 1: {// restore the queue dispatch_resume (concurrentQueue);} break ;}

 

During development, we may use the thread lock function, such as ticketing and ticket snatching. When there is no thread lock:I walked into the ticket buying Hall, and the ticket buyers were not in line. I was very difficult to squeeze into the window. When I was planning to pay for the ticket, someone next to me had already handed the money to the conductor. Although your thread has started to execute the ticket buying method, when you get the ticket, that is, to reduce the number of votes by a moment, the CPU will interrupt your thread and start executing other threads, when the CPU returns to continue executing your thread, the ticket is gone. When a thread lock exists :*I walked into the ticket purchase Hall, and all the people who bought the tickets were waiting in line. When I arrived at the counter, I could ensure that the key process of buying the tickets, that is, reporting the station, paying for the money, and obtaining the tickets were not disturbed, I use the thread lock to lock this key process to ensure that I can buy tickets smoothly. Here I name it GCDLockViewController. The specific. m code is as follows:
# Import "GCDLockViewController. h "@ interface GCDLockViewController () {NSLock * mylock;} @ end @ implementation GCDLockViewController-(void) viewDidLoad {[super viewDidLoad]; self. view. backgroundColor = [UIColor whiteColor]; // instantiate a thread lock mylock = [NSLock new]; # pragma mark === thread lock ===_ _ block int ticketNum = 10; dispatch_queue_t concurrent = dispatch_get_global_queue (0, 0); for (int index = 0; index <15; index ++) {dispatch_async (concurrent, ^ {// [mylock lock]; // if (ticketNum> 0) {// ticketNum --; // NSLog (@ "% d tickets remaining", ticketNum); // [mylock unlock]; // The parameter is generally a self-related variable. Multiple Threads only access @ synchronized (self) {if (ticketNum> 0) {ticketNum --; NSLog (@ "% d tickets remaining", ticketNum) ;}}}) ;}}@ end

 

 

 

 

Related Article

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.