1. What is multithreading?

  • multithreadingA technique that enables concurrent execution of multiple threads to improve overall processing performance.
  • The CPU can only handle one thread at a time, and multiple threads execute concurrently. In fact, the CPU schedules (switches) between multiple threads very quickly. If the CPU schedules threads fast enough, it creates the illusion of multiple threads executing concurrently
  • The stack size of the main thread is 1M, which is very, very valuable
  • The stack space size of the child thread is 512K memory space

advantage

  • Give full play to the advantages of multi-core processor, assign tasks of different threads to different processors, and truly enter the state of “parallel computing”

disadvantages

  • New threads consume memory controls and CPU time, and too many threads degrade system performance.

2. What is the difference between processes and threads?

  • Process: a running program that allocates memory for the program. Each process has its own virtual memory space. (The dynamic process by which a program runs)
  • Thread: A thread is an independent path of execution in a process (control unit). A process contains at least one thread, that is, the main thread can place time-consuming execution paths (such as network requests) in other threads.

Process and thread comparison

  • Thread is the smallest unit of CPU invocation
  • A process is the unit of CPU allocation and scheduling
  • A program can correspond to multiple processes, a process can have multiple threads, but there must be at least one thread
  • Threads within the same process share process resources

3. How do threads communicate with each other?

  • Communication between threads is the embodiment of one thread passing data to another thread
  • After a particular task has been executed in one thread, the task continues in another thread

4. What are the multithreading schemes for iOS?

5. What is communist Party of China?

  • GCD(Grand Central Dispatch), also known as big Central scheduling, encapsulates thread operations, adds many new features, optimizes internal efficiency, and provides simplicityC interface, which is also recommended by Apple.

6.GCD queue type?

  • Concurrent queue (Concurrent Dispatch Queue)

    Enables concurrent execution of multiple tasks (automatically enabling multiple threads to execute tasks simultaneously)

    Concurrency is only available in asynchronous (dispatch_asyncFunction
  • Serial queue (Serial Dispatch Queue)

    Let tasks be executed one after another (after one task is completed, the next task is executed) in FIFO order.

7. What are synchronous and asynchronous task dispatch?

GCD multithreading often uses the dispatch_sync and dispatch_async functions to add tasks to a specified queue, synchronous and asynchronous, respectively

  • Synchronization means blocking the current thread until the added time-consuming task Block is complete before the function can return and subsequent code can continue
  • Asynchronous means that after a task is added to a queue, the function returns immediately and the following code can be executed without waiting for the completion of the added task. Asynchronous submission cannot determine the task execution order

8. Dispatch_after used?

  • This function allows the submitted task to be executed after a specified time, that is, delayed execution.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@" run in 10 seconds ")});Copy the code

9. Use of dispatch_group_t (group dispatch)?

  • Group scheduling can wait for a group of operations to complete after the execution of subsequent tasks
dispatch_group_t group = dispatch_group_create(); Dispatch_group_async (dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// request 1}); Dispatch_group_async (dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// request 2}); Dispatch_group_async (dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// request 3}); Dispatch_group_notify (group, dispatch_get_main_queue(), ^{// NSLog(@" all tasks completed, refresh interface "); });Copy the code

10. How to use dispatch_semaphore?

  • Used to control the maximum number of concurrent requests
  • This prevents resource looting

There are three functions associated with it

Dispatch_semaphore_create, // Create the maximum number of concurrent dispatch_semaphore_wait. // dispatch_semaphore_signal is executed (0 waits)Copy the code

11. What is NSOperation?

  • NSOperation is a GCD-based wrapper that wraps threads into operations to be performed without managing thread lifecycle and synchronization, and is more controllable than GCD

  • You can add operation dependencies to control the execution sequence, set the maximum number of concurrent operations in the operation queue, and cancel operations

12. How does NSOperation implement operation dependency?

  • By adding dependencies between tasks, you can set the execution sequence of tasks

The following example demonstrates the effect of setting dependencies.

NSOperationQueue *queue=[[NSOperationQueue alloc] init]; NSBlockOperation *operation1=[NSBlockOperation blockWithBlock :^(){NSLog(@") %@",[NSThread currentThread]); }]; NSBlockOperation *operation2=[NSBlockOperation blockOperationWithBlock:^(){NSLog(@" perform the second operation, thread: %@",[NSThread currentThread]); }]; NSBlockOperation *operation3=[NSBlockOperation blockOperationWithBlock:^(){NSLog(@" %@",[NSThread currentThread]); }]; // addDependency [operation1 addDependency:operation2]; [operation2 addDependency:operation3]; // Add operations to queue [queue addOperation:operation1]; [queue addOperation:operation2]; [queue addOperation:operation3];Copy the code

13. Can I put time-consuming operations in NSNotification?

  • If notifications are sent from an asynchronous thread, then time-consuming operations can be performed
  • If notifications are sent in the main thread, then time-consuming operations cannot be performed

14. Tell me some examples of thread safety that you have used in your work.

  • UIKit(must be on main thread)
  • FMDBDataBaseQueue(Serial queue)

15. Dispatch_barrier_ sync (a) use?

A Dispatch barrier allows the creation of a synchronization point in a concurrent queue. When a barrier is encountered in a concurrent queue, it delays execution of the barrier’s block until all blocks submitted before the barrier have finished. At this point, the Barrier Block starts executing itself. After that, the queue continues to perform operations normally

16. Dispatch_set_target_queue?

  • The dispatch_set_target_queue function has two functions: first, it changes the execution priority of the queue; Second, the target queue can become the execution hierarchy of the original queue.
dispatch_set_target_queue(dispatch_object_t object, dispatch_queue_t queue);
Copy the code
  • The first parameter is the queue to execute the change (primary and global queues cannot be specified)
  • The second argument is the destination queue (specifies the global queue). What is the main thread relative to

17. When do you choose GCD and NSOperation in a project?

  • The advantage of using NSOperation in the project is that NSOperation is highly abstract to the thread. Using NSOperation in the project will make the program structure of the project better. The design idea of subclassing NSOperation has the advantage of object-oriented (reuse and encapsulation), making the implementation supported by multithreading. The interface is simple and recommended for complex projects.
  • The advantage of using GCD in the project is that GCD itself is very simple and easy to use. For uncomplicated multi-threaded operation, it will save the amount of code, and the use of Block parameter will make the code more readable. It is recommended to use it in simple projects.

18. Talk about the differences between OperationQueue and GCD and the advantages of each

  • GCD is a pure C API, NSOperationQueue is based on the OC version of GCD
  • GCD only supports QUEUE columns that support FIFO, and NSOperationQueue can easily adjust the order of execution lines and set the maximum number of concurrent requests
  • NSOperationQueue can easily set up dependencies between operations, whereas GCD requires a lot of code to do so
  • The NSOperationQueue support supports KVO to monitor whether an operation isExecuted, isFinished, or cancelled.
  • The execution speed of GCD is faster than that of NSOperationQueue. Tasks are not too interdependent :GCD tasks are dependent on each other or want to listen to the execution of the task :NSOperationQueue

19. How does the GCD cancel threads?

The GCD currently has two ways to cancel threads:

  • Case 1:dispatch_block_cancelLike NSOperation, you can cancel threads that have not yet executed. But there is no way to cancel a thread that is executing.
dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_block_t block1 = dispatch_block_create(0, ^{ NSLog(@"block1"); }); dispatch_block_t block2 = dispatch_block_create(0, ^{ NSLog(@"block2"); }); dispatch_block_t block3 = dispatch_block_create(0, ^{ NSLog(@"block3"); }); dispatch_async(queue, block1); dispatch_async(queue, block2); dispatch_async(queue, block3); dispatch_block_cancel(block3); / / cancel block3Copy the code
  • Case 2: UseTemporary variable +returnMethod to cancel a Block being executed
__block BOOL gcdFlag= NO; // dispatch_async(dispatch_get_global_queue(0, 0), ^{for (long I =0; i<1000; I ++) {NSLog(@" doing the I :%ld", I); sleep(1); If (gcdFlag==YES) {// Judge and terminate NSLog(@" terminate "); return ; }}; }); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@" I'm going to stop "); gcdFlag = YES; });Copy the code

20.NSOperation cancel thread mode?

  • 1. Cancel an operation that has not been performed
NSOperationQueue *queue1 = [[NSOperationQueue alloc]init];
NSBlockOperation *block1 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"block11");
}];
NSBlockOperation *block2 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"block22");
}];
NSBlockOperation *block3 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"block33");
}];
[block3 cancel];
[queue1 addOperations:@[block1,block2,block3] waitUntilFinished:YES];
Copy the code
  • 2. Remove all operations from the queue, but the ongoing operations cannot be removed
[queue1 cancelAllOperations];
Copy the code
  • 3. Suspend the queue, so that the queue task is no longer executed, but the ongoing operation cannot be suspended
queue1.suspended = YES;
Copy the code
  • 4. You can customize NSOperation to cancel the ongoing operation. Basically, it intercepts the main method
When any operation is executed, the start method is called first. The start method updates the state of the operation (filtering operations, for example, filtering out operations in the "cancel" state). 2. After filtering by the start method, the main method is called only for normally executable operations. 3. Override the entry method (main) of the operation to specify the task performed by the operation. 4. The main method is executed asynchronously on child threads by default.Copy the code

21. What is thread safety?

  • A resource may be shared by multiple threads, which means that multiple threads may access the same resource
  • For example, multiple threads access the same object, the same variable, the same file
  • When multiple threads access the same resource, data corruption and data security issues can easily occur

22. What are the thread-safe handling methods?

  • lock
  • Synchronous execution

23. How to understand GCD deadlock?

  • The so-called deadlock is usually two operations waiting for each other to complete, causing an infinite loop, so that both operations can not be performed, resulting in a deadlock

24. What are spinlocks and mutex?

  • Spin locks wait busy: When a locked resource is accessed, the caller thread does not sleep, but loops there until the locked resource releases the lock.
  • The mutex sleeps: When a locked resource is accessed, the caller thread sleeps so that the CPU can schedule other threads to work. Until the locked resource releases the lock. The dormant thread is awakened.

25.OC What locks do you know?

  • Os_unfair_lock ios10 began

  • OSSpanLock ios10 abandoned

  • Dispatch_semaphore is recommended and has good performance

  • dispatch_mutex

  • Dispatch_queue serial

  • NSLock encapsulates mutex

  • @synchronized has the worst performance

26: When are spins and mutexes used?

When is it cost-effective to use a spin lock?

  • Threads are expected to wait a short time for locks
  • Locking code (critical sections) is often invoked, but contention rarely occurs
  • CPU resources are not tight
  • Multicore processor

When is it cost-effective to use a mutex?

  • The thread is expected to wait a long time for the lock
  • Single-core processor
  • There are IO operations in the critical area
  • Critical section code complex or large loop
  • Critical sections are very competitive

27. Code analysis 1, does this function take time? The output

dispatch_queue_t queue = dispatch_queue_create("test", nil); dispatch_async(queue, ^{ NSLog(@"1"); sleep(1); }); dispatch_async(queue, ^{ NSLog(@"2"); sleep(1); }); dispatch_sync(queue, ^{ NSLog(@"3"); sleep(1); }); Does this function take time? : 3 seconds for this function to output? : 123Copy the code
  • Serial queue asynchronous execution will open a new thread, synchronous execution will not open a thread, in a serial queue, the sequential execution takes 3 seconds, printing 123;

  • Concurrency: Tasks are removed from the sequence in FIFO and run concurrently, which can be completed in any order. It automatically starts multiple threads executing tasks simultaneously

  • Serial: Tasks are executed one by one in FIFO from a sequence. Only one task is scheduled at a time, and tasks in the queue are executed one after another (after one task is completed, the next task is executed) and only one thread is opened

28. Code analysis two, print the result

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
    NSLog(@"1");
    [self performSelector:@selector(test) withObject:nil afterDelay:0];
    NSLog(@"3");
});

- (void)test{
    NSLog(@"2");
}
Copy the code
  • Print 1, 3
  • PerformSelector After is based on the timer customizer, and the timer is implemented based on runloop; Task 2 In child threads, runloop is disabled by default, so do not execute 2

29. What is the print result of the following code?

- (void)test{
    NSLog(@"2");
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSThread *thread = [[NSThread alloc]initWithBlock:^{
        NSLog(@"1");
    }];
    [thread start];
    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
}
Copy the code
  • Print 1
  • The thread is destroyed when start is finished. Task test cannot be executed
The statement
The answer to the interview questions in this article is based on the collection of various gods, the answer is not necessarily the most comprehensive, the most appropriate, if there is a question, welcome to actively discuss.
Reference article:

www.jianshu.com/p/ca1ff3749… Github.com/ReginaVicky…