Multithreading technology (NSThread, OperationQueue, GCD) and iosnsthread

Source: Internet
Author: User

Multithreading technology (NSThread, OperationQueue, GCD) and iosnsthread

In the previous blog, if asynchronous requests were used, they were also used by third parties. They were not familiar with iOS multithreading. In fact, multithreading is quite important. If you have learned the operating system before, it is easier to understand multithreading, today we will make a small demo to learn more about multithreading in iOS. It may be boring but practical.

Multithreading is still widely used, and we have to say nothing about it. The following two are the final results of our experiment today. They should be comprehensive, let's use graphs to analyze specific functions:

I. preparation phase

1. Whether you use code writing, storyboard, or xib, initialize the required control for use.

2. Click the test UI Button. The code for changing the label color is as follows:

1 // change the lable color and exchange the red-green color. 2-(IBAction) tapTestButton :( id) sender {3 static int I = 1; 4 if (I = 1) {5 _ testLabel. backgroundColor = [UIColor redColor]; 6 I = 0; 7} 8 else 9 {10 _ testLabel. backgroundColor = [UIColor greenColor]; 11 I = 1; 12} 13 14}

 

3. Get the image from the network and use the main thread to display the process call status

1 // obtain image data from wang 'lu 2-(NSData *) getImageData 3 {4 5 _ count ++; 6 int count = _ count; 7 8 NSData * data; 9 [NSThread sleepForTimeInterval: 0.5]; 10 data = [NSData dataWithContentsOfURL: [NSURL URLWithString: IMAGEURL]; 11 12 NSString * str = [NSString stringWithFormat: @ "% d. thread % @ finished ", count, [NSThread currentThread]; 13 // the data request task is handled by other threads, so the content of LogTextView is updated by the main thread, only the main thread can update UI14 [self defined mselecw.mainthread: @ selector (updateTextViewWithString :) withObject: str waitUntilDone: YES]; 15 return data; 16}

 

4. The above uses the main thread to call the updateTextViewWithString method, because only the main thread can update the UI, updateTextViewWithString: This method is responsible for displaying the thread execution information on the View, the Code is as follows:

1 // display the image Request status on ViewController 2-(void) updateTextViewWithString :( NSString *) str3 {4 NSString * old_str = [NSString stringWithFormat: @ "% @ \ n % @", _ logTextView. text, str]; 5 6 _ logTextView. text = old_str; 7 // change the Label color for easy observation 8 [self tapTestButton: nil]; 9}

 

5. Load the requested image to the ImageView.

1 // update image 2-(void) updateImageWithData :( NSData *) data3 {4 UIImage * image = [UIImage imageWithData: data]; 5 [_ testImage setImage: image]; 6}

 

6. Load the image, that is, the requested data is displayed on the ImageView.

1 // request data from other threads. The main thread will update UI2-(void) loadImageWithThreadName :( NSString *) threadName3 {4 [[NSThread currentThread] setName: threadName]; 5 6 NSData * data = [self getImageData]; 7 [self defined mselec1_mainthread: @ selector (updateImageWithData :) withObject: data waitUntilDone: YES]; 8}

 

2. In various ways

1. synchronous request image testing. The request data and update UI are all executed sequentially in the main thread. In this way, the UI will become stuck when the data is requested. The Code is as follows;

1 // synchronous request image, view blocking, because the main thread is occupied, unable to update the view 2-(IBAction) tapButton :( id) sender {3 NSData * data = [self getImageData]; 4 [self updateImageWithData: data]; 5}

 

2. NSThread creates a thread for testing. Using the detachNewThreadSelector method to create a new thread automatically starts and runs without calling the start method. The Code is as follows:

1 // NSThread2-(IBAction) tapButton2 :( id) sender {3 // click a button to create a new thread to request image data 4 5 [NSThread detachNewThreadSelector: @ selector (loadImageWithThreadName :) toTarget: self withObject: @ "NSThread"]; 6}

   

3. Use NSInvocationOperation to create a new call operation and add it to the queue for execution. The Code is as follows:

1 // NSInvocationOperation 2-(IBAction) tapInvocationOperation :( id) sender {3 // instantiate a call operation to execute Data Request 4 NSInvocationOperation * invocationOperation = [[NSInvocationOperation alloc] failed: self selector: @ selector (loadImageWithThreadName :) object: @ "Invocation"]; 5 6 // The above call operation needs to be put into the call queue for execution 7 // create the operation queue 8 NSOperationQueue * operationQueue = [[NSOperationQueue alloc] init]; 9 10 // put the above call operations in the Operation queue, the queue will automatically enable a thread to call the method we specified 11 [operationQueue addOperation: invocationOperation]; 12}

 

4. Create a block operation and add it to the queue for execution. The Code is as follows:

1 // BlockOperation 2-(IBAction) tapBlockOperation :( id) sender {3 _ weak _ block ViewController * copy_self = self; 4 5 // create BlockOperation 6 NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock: ^ {7 [copy_self loadImageWithThreadName: @ "Block"]; 8}]; 9 10 // Add to Operation queue 11 NSOperationQueue * operationQueue = [[NSOperationQueue alloc] init]; 12 [operationQueue addOperation: blockOperation]; 13 14 // another Method 15 [operationQueue addOperationWithBlock: ^ {16 [copy_self loadImageWithThreadName: @ "Block"]; 17}]; 18 19}

 

5. Serial queue in GCD:

1 // serial queue 2-(IBAction) tapGCDserialQueue :( id) sender {3 // create a serial queue 4 dispatch_queue_t serialQueue = dispatch_queue_create ("mySerialQueue", queue ); 5 6 7 _ weak _ block ViewController * copy_self = self; 8 // asynchronous execution queue 9 dispatch_async (serialQueue, ^ {10 [copy_self loadImageWithThreadName: @ "Serial"]; 11}); 12 13}

 

6. Parallel queues in GCD:

1 // parallel queue 2-(IBAction) tapGCDConcurrentQueue :( id) sender {3 // create parallel queue 4 dispatch_queue_t concurrentQueue = dispatch_queue_create ("myConcurrentQueue", queue ); 5 _ weak _ block ViewController * copy_self = self; 6 // asynchronous execution queue 7 dispatch_async (concurrentQueue, ^ {8 [copy_self loadImageWithThreadName: @ "Concurrent"]; 9}); 10 11}

The above is the method corresponding to each button, and the following is the execution result:

Iii. synchronization between threads (adding a synchronization lock for our threads)

When talking about multithreading in the operating system, there is a term called dirty data, which is caused by multiple threads operating on the same resource. Next, modify the code to make the data problematic, then we use the synchronization lock to solve this problem.

1. There are two statements in the getImageData method (the 3rd methods in Title 1. This is used to display the thread label. The above labels are not repeated.

1     _count ++;2     int count = _count;

Add a latency between the two statements as follows:

    _count ++;    [NSThread sleepForTimeInterval:1];    int count = _count;

If running, there will be a lot of labels that are repeated. One ,__ count is a member variable. Multiple Threads operate on this variable, so there will be inconsistent labels, add the synchronization lock.

(1) Use NSLock to apply a synchronization lock. The Code is as follows:

1 // use NSLock to lock 2 [_ lock]; 3 _ count ++; 4 [NSThread sleepForTimeInterval: 1]; 5 int count = _ count; 6 [_ lock unlock];

(2) Add a synchronization lock through @ synchronized. The Code is as follows:

1 // use synchronized to lock 2 int count; 3 @ synchronized (self) {4 _ count ++; 5 [NSThread sleepForTimeInterval: 1]; 6 count = _ count; 7}

The running effect before and after the lock is as follows:

Today's blog has a lot of content. If you have been familiar with Java's multi-threaded things or multithreading in other languages, it should be difficult to understand.

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.