IOS-dispatch_semaphore and NSOperationQueue concurrency, nsoperationqueue

Source: Internet
Author: User

IOS-dispatch_semaphore and NSOperationQueue concurrency, nsoperationqueue

Concurrency: Run multiple tasks at the same time. It is also called "colopicity", which refers to the ability to process multiple synchronous activities.

Parallel: Two concurrent tasks occur simultaneously.

Concurrency is not necessarily parallel, and concurrency does not necessarily occur at the same time.

 

For example:

There are two different express deliveries to the destination, there are two solutions:

(1) One courier delivers two parcels to the corresponding destination respectively. (Concurrency)

(2) Two couriers send one to their destination at the same time. (Parallel)

 

In iOS, it is often seen that such a requirement is that a method must wait for the execution of another method to complete the corresponding processing, such as some network requests, the second request needs to be processed based on the return value of the previous request, so we cannot allow both requests to go to the request network at the same time. The following is a record of how to control concurrency through GCD and NSOperationQueue.

Dispatch_semaphore

Semaphores are an integer value with an initial count value. semaphores generally support two operations: Notification and wait. When the signal is notified, the Count value will increase. When the semaphore waits on the thread, the thread will be blocked if necessary until the signal is notified with a value greater than 0, then the thread will reduce the count and continue to work.

Operations related to three semaphores in GCD:

Create a dispatch_semaphore_create semaphore

Dispatch_semaphore_signal send notification

Dispatch_semaphore_wait semaphore waiting

_ Block Partition sem = dispatch_semaphore_create (0); dispatch_queue_t queue = dispatch_queue_create ("testBlock", NULL); dispatch_async (queue, ^ {for (int I = 0; I ++) {NSLog (@ "I value: % d", I);} dispatch_semaphore_signal (sem) ;}); dispatch_semaphore_wait (sem, DISPATCH_TIME_FOREVER ); for (int j = 0; j <10; j ++) {NSLog (@ "j value: % d", j );}

The running result is:

 

NSOperationQueue

If no dependency is added:

NSOperationQueue * queue = [[NSOperationQueue alloc] init]; queue. maxConcurrentOperationCount = 10; NSBlockOperation * operation1 = [NSBlockOperation blockOperationWithBlock: ^ {for (int I = 0; I <1000; I ++) {NSLog (@ "execution concurrency queue 1: % d ", I) ;}}]; NSBlockOperation * operation2 = [NSBlockOperation blockOperationWithBlock: ^ () {for (int I = 0; I <1500; I ++) {NSLog (@ "execution concurrency queue 2: % d", I) ;}}]; [queue addOperation: operation1]; [queue addOperation: operation2];

Running result:

Two NSOperation statements are printed concurrently.

 

After adding dependency control:

NSOperationQueue * queue = [[NSOperationQueue alloc] init]; queue. maxConcurrentOperationCount = 10; NSBlockOperation * operation1 = [NSBlockOperation blockOperationWithBlock: ^ {for (int I = 0; I <1000; I ++) {NSLog (@ "execution concurrency queue 1: % d ", I) ;}}]; NSBlockOperation * operation2 = [NSBlockOperation blockOperationWithBlock: ^ () {for (int I = 0; I <1500; I ++) {NSLog (@ "execution concurrency queue 2: % d", I) ;}}]; [operation1 addDependency: operation2]; // Add dependency, operation1 depends on operation2 to continue [queue addOperation: operation1]; [queue addOperation: operation2];

 

Printed result:


IOS multi-thread programming, can there be multiple NSOperationQueue?

Yes! Each operationQueue is independent of each other.

IOS shake to determine how many seconds it takes

CMMotionManager * _ motionManager = [[CMMotionManager alloc] init]; NSOperationQueue * _ operationQueue = [[NSOperationQueue alloc] init]; BOOL _ isShake; // whether to shake BOOL _ isOver = NO; // whether to shake NSInteger _ beginTimestamp = 0; // The timestamp _ motionManager. accelerometerUpdateInterval = 1;-(void) initShake {[_ motionManager startAccelerometerUpdatesToQueue: _ operationQueue withHandler: ^ (CMAccelerometerData * latestA Cc, NSError * error) {dispatch_sync (dispatch_get_main_queue (), ^ (void) {// synchronize all operations @ synchronized (_ motionManager) {_ isShake = [self isShake: _ motionManager. accelerometerData]; if (_ beginTimestamp = 0 & _ isShake = YES) {NSLog (@ the lottery starts); _ beginTimestamp = [[NSDate date] timeIntervalSince1970];} if (_ beginTimestamp! = 0 & _ isShake = NO) {_ isOver = YES;} // if (_ isOver) {// stop shaking detection event [_ motionManager stopAccelerometerUpdates]; // cancel other requests queued in the queue [_ operationQueue cancelAllOperations]; NSInteger currentTimestamp = [[NSDate date] timeIntervalSince1970]; // shake duration NSInteger second = currentTimestamp-_ beginTimestamp; NSLog (@ shake end, duration: % d, second) ;}}}) ;}] ;}- (BOOL) isShake :( CMAccelerometerData *) newestAccel {BOOL isS Hake = NO; // If the acceleration speed in any of the three directions is greater than 1.5, it is regarded as shaking. If the acceleration speed is less than 1.5, it is deemed that the lottery is over.

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.