Creation and addition of iOS multithreaded semaphores
This article introduces the relevant knowledge of "the creation and increase of iOS multithreaded semaphores". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
# # semaphore
Signal creation, where value is the initial signal value, which is mainly used to control the number of concurrency
Dispatch_semaphore_create (long value)
Signal waiting function, dsema is the signal, timeout is the waiting time point, during the waiting time point, only the signal value of the signal dsema is greater than or equal to 1 will be released, and continue to execute; at the same time, the signal value minus 1
Dispatch_semaphore_wait (dispatch_semaphore_t dsema, dispatch_time_t timeout)
Increase the signal value, and increase the signal value of the corresponding dsema by 1 for each use
Dispatch_semaphore_signal (dispatch_semaphore_t dsema)
Asynchronous execution of program
-(void) asyncTest {dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); NSMutableArray * array = [NSMutableArray array]; for (int index = 0; index < 10; index++) {dispatch_async (queue, ^ () {[array addObject: [NSNumber numberWithInt:index]]; [NSThread sleepForTimeInterval:2] NSLog (@ "thread%@----index:% d", [NSThread currentThread], index);});}
Synchronous execution of program
-(void) semaphoreTest {dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_semaphore_t semaphore = dispatch_semaphore_create (1); NSMutableArray * array = [NSMutableArray array]; for (int index = 0; index < 10; index++) {dispatch_async (queue, ^ () {dispatch_semaphore_wait (semaphore, DISPATCH_TIME_FOREVER) / / this function itself is a judgment function, and only if this function passes (with a signal) will it continue to execute [array addObject: [NSNumber numberWithInt:index]]; NSLog (@ "thread%@----index:% d", [NSThread currentThread], index); [NSThread sleepForTimeInterval:2]; dispatch_semaphore_signal (semaphore);}) }} "creation and addition of iOS multithreaded semaphores" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!