8, multithreading

[pictures uploaded]… (1)]* process

Is a program with independent function, a running activity on a data set, the process is the system of resource allocation and scheduling of an independent unit. A process can contain multiple threads, but at least one thread. The memory resources between processes are independent of each other. A multi thread
thread consumption of resources is a physical process, is the basic unit of CPU scheduling and dispatching, it is smaller than the process of basic unit can operate independently. They basically do not have thread system resources, only a little essential in the operation of the resources (such as the program counter, and a set of registers the other thread stack), but it can belong to a process of sharing all resources owned by the
process. A thread can be created and destroyed another thread; multiple threads of the same process can be executed concurrently.
multi thread disadvantages advantages: improve the efficiency of the program, logic: more complex, deadlock

  • The queue iOS squadron column is divided into a serial queue, a parallel queue
Queue = dispatch_queue_create dispatch_queue_t / / concurrent queues (test, DISPATCH_QUEUE_CONCURRENT) / / serial queue dispatch_queue_create (com.hackemist.SDWebImageCache, DISPATCH_QUEUE_SERIAL); note: the queue is completely finished with release dispatch_release (quequ);
  • Task synchronization
Asynchronous tasks (quequ_chuanxing, dispatch_async / ^{your Code;}); swift 3 DispatchQueue.global (.Async) {} / / synchronous task dispatch_sync (quequ_chuanxing, NSLog ^{(@ "asynchronous tasks");}); / / func (function3) delay execution {let delay = DispatchTime.now (DispatchTimeInterval.seconds) + DispatchQueue.main.asyncAfter (deadline: (15) delay) {self.label = UIColor.blue?.backgroundColor print ("hhhh")}}
8, multithreading

The task attribute determines whether the code is executed in the new thread, which determines the order in which the task is executed

Serial queue Parallel queue
Synchronization task Sequential execution, blocking the primary thread, and not opening new threads Sequential execution, blocking the primary thread, and not opening new threads
Asynchronous task asyns The order of execution, not blocking the main thread, open a new thread (the people inside are in another non main thread) Cross execution does not block new threads and opens new threads (each thread of the task is different)

Multithreaded implementation

NSThread thread declaration cycle, the program ape own management,
, GCD, c style,
, NSOperation, object-oriented, control task number

Void dispatch_barrier_async (dispatch_queue_t, queue, dispatch_block_t, block);

A dispatch barrier allows you to create a synchronization point in a concurrent queue. When a barrier is encountered in a concurrent queue, he will delay the execution of the barrier’s block and wait for all blocks execution before the barrier ends. At this point, barrier block himself began executing. After that, the queue continues to perform the normal operation. The
call is always returned immediately after the barrier block is committed and will not wait until block is executed. When barrier block arrives at the forefront of a concurrent queue, he does not execute immediately. Instead, the queue will wait until all the currently executing blocks ends. By this time, barrier began to perform it himself. All blocks submitted after the barrier block will wait until barrier block is finished.
this is invalid in globalqueue because the global queue assigned by the system each time is not necessarily the same queue

Thread group
Dispatch_group_t = dispatch_group_create (serviceGroup); / / create a thread queue dispatch_group_enter (serviceGroup); / / the current task queue (serviceGroup); / / dispatch_group_leave / / dispatch_group_notify when the current task queue method after all tasks are out of the queue to go (serviceGroup, dispatch_get_main_queue), (^{}); Swift let group = DispatchGroup.init (3) (group.enter group.leave) (group.notify) (queue: DispatchQueue.main) {print} ("end")
Mutex thread lock

At the same time, only one thread can access this resource

@synchronized (self.failedURLs) {isFailedUrl = [self.failedURLs containsObject:url]}
NSOperationQueue thread queue
A thread queue is a container for NSOperation, which is used primarily to manage Operation. A operation is added to Queue and is no longer required for start.
Create a [[NSOperationQueuealloc]init] method; (void) addOperation: (NSOperation * OP); / / add a operation to queue will immediately execute asynchronously - (void) addOperations: (NSArray< NSOperation *> *) OPS waitUntilFinished: (BOOL) wait NS_AVAILABLE (10_6, 4_0); / / add a group of Operation to queue, wait. Whether the current thread is blocked until the inside, thread end - (void) addOperationWithBlock: (void (^) (void) block) NS_AVAILABLE (10_6, 4_0); / / create a operation directly with block, and added - (void) cancelAllOperations; / / cancel the current queue all tasks - (void) waitUntilAllOperationsAreFinished; / / the current thread is blocked, know that the task completed property @property (readonly, copy) NSArray < __kindof NSOperation *> *operation S; / / the current cohort (readonly) NSUInteger @property operation operationCount NS_AVAILABLE (10_6, 4_0); / / the current queue number of Operation @property NSInteger maxConcurrentOperationCount; / / the maximum number of concurrent, the default is no limit @property (getter=isSuspended) BOOL suspended; / / hang up the queue, only hang has not been executed in execution the @property NSQualityOfService qualityOfService NS_AVAILABLE will not be suspended (10_10, 8_0); / * your task is to tell the system what to do in the operation and user interaction tasks, these tasks are usually related to refresh the UI level, such as animation, these tasks need to be initiated by the user NSQualityOfServiceUserInitiated in a flash and need to get results immediately task. For example, slide To load the data for subsequent cell display scroll view, these tasks with subsequent user interaction, NSQualityOfServiceUtility may need to spend some time on the task in a few seconds or shorter time, these tasks do not need to immediately return the results, such as downloading tasks, these tasks may take a few seconds or a few NSQualityOfServiceBackground minutes of these tasks are not visible to the user, such as the background of the backup operation may take a long time for these tasks, a few minutes or even hours NSQualityOfServiceDefault priority between user-initiated and utility, use the default when no QoS information, the developers should not use this value to set their own tasks (nullable, assign / * * / @property actually reta In dispatch_queue_t underlyingQueue// * /) of the current queue gcdqueue @property (class, readonly, strong, nullable) NSOperationQueue *currentQueue NS_AVAILABLE (10_6, 4_0); / / class attribute, used with other inter thread communication @property (class, readonly, strong) NSOperationQueue *mainQueue NS_AVAILABLE (10_6, 4_0); / / class attribute, used with other threads communication
The equivalent of virtual class, call the start implementation of the main method, the direct use of the words and do nothing, if you use a subclass of it is best to write in the main method, operation does not add to the queue it is executed in the main thread, if you join the queue will open a new thread. The methods used by subclasses are written in main, not written in start, or other states will not automatically be maintained.
- (void) start; / / to the method of (void) main; / / began after the implementation of the method / cancellation method and judgment, when operation is in the implementation of cancel is not, but it will change the value of iscacelled, so the main method (such as sdwebimage), is only cancel in many places the manual judgment, and then exit the thread executing @property (readonly, getter=isCancelled) - (void) BOOL cancelled; cancel; / / is running @property (readonly, getter=isExecuting) BOOL executing; / / is executed @ property (readonly, getter=isFinished) BOOL finished; / / is asynchronous, but only asynchronous display 0, the default is synchronization. But added to the queue, and add a block asynchronous @property (readonly, getter=isConcurrent) BOOL concurrent; / / To be depreca Ted; use and override'asynchronous'below @property (readonly, getter=isAsynchronous) BOOL asynchronous NS_AVAILABLE (10_8, 7_0); / / ready @property (readonly, getter=isReady) BOOL ready; / / add on, remove the dependence, then add OP before it own - (void) addDependency: (NSOperation * OP); - (void) removeDependency: (NSOperation *) op; @property (readonly, copy) NSArray< NSOperation *> *dependencies typedef NS_ENUM; / / priority queue (NSInteger, NSOperationQueuePriority) {NSOperationQueuePriorityVeryLow = -8L, NSOperationQueuePriorityLow = -4L, NSOperationQueuePriorityNormal = 0, NSOperationQueuePriorityHigh = 4, NSOperationQueuePriorityVeryHigh = 8}; @property NSOperationQueuePriority queuePriority; / /. After the completion of the call for block @property (nullable, copy) void (^completionBlock) (void) NS_AVAILABLE (10_6, 4_0); / / blocking the current thread - (void) waitUntilFinished NS_AVAILABLE (10_6, 4_0); / / thread priority 0 - 1 @property double threadPriority NS_DEPRECATED (10_6, 10_10, 4_0, 8_0); / / tell this system is used for @property NSQualityOfService qualityOfService NS_AVAILABLE thread (10_10, 8_0); / / name of @property (nullable, copy) NSString *name NS_AVAILABLE (10_10, 8_0);
+ (instancetype) blockOperationWithBlock: (void (block ^) (void)); / / initialization method - (void) addExecutionBlock: (void (block ^) (void)); / / add block will open a new thread asynchronous @property (readonly, copy) NSArray< (void ^); (void) > *executionBlocks; / / has been added to block.
/ / initialization method - (nullableinstancetype) initWithTarget: (ID) target selector: (SEL) sel object: (nullableid) Arg; (instancetype) - initWithInvocation: (NSInvocation * INV) NS_DESIGNATED_INITIALIZER; @property (readonly, retain) NSInvocation *invocation; / / return value? @property (nullable, readonly, retain) ID result;

The two is actually equivalent to the already wrapped Operation