Latest interview questions for iOS senior engineers in 2021_ Multithreading

Posted by mgm_03 on Wed, 09 Mar 2022 10:34:33 +0100

1. What is the difference between process and thread?

Process is a program with certain independent functions. It is a running activity about a data set. It is the basic unit for the operating system to allocate resources.

Process refers to an application running in the system, which is the execution process of a program,We can understand it as one on the mobile phone app.

Each process is independent. Each process runs in its dedicated and protected memory space and has all the resources required for independent operation

The smallest unit of program execution flow. Thread is an entity in the process.

A process wants to perform a task,There must be at least one thread.When the application starts, the system will start a thread by default,That is, the main thread

Starting a thread requires a certain amount of memory space (by default, the main thread occupies 1 M,The child thread occupies 512 KB),If you start a large number of threads, it will occupy a lot of memory space and reduce the performance of the program

The more threads, CPU The greater the overhead on the scheduling thread

2. What are the ways of process communication between apps?

URL Scheme 
advantage
 This jump method is very flexible, just in.plist Simple processing is done in the file, and then only simple logical processing is required locally, which can also be used openURL To open App The corresponding controller, which you want to turn on URL Scheme It can be obtained dynamically from the server. Then it is very simple to realize the dynamic jump.
URL Scheme The way parameters are passed is also the same as URL Consistent, simply in URL Add the corresponding parameters to the.
This page Jump is indistinguishable through URL Scheme Jump can be seamless in H5 Jump between the page and the original page to transfer values, rather than making more logical judgments.
shortcoming
 Write in info.plist In the file Scheme It may be obtained by some decompilation means.
URL Scheme May be hijacked and transferred to security risks

Keychain
 Advantages and disadvantages
 Data is not stored in App of Sanbox Even if deleted App,The data is still stored in keychain Yes. If reinstalled app,Also available from keychain Get data.
keychain The data can be used group Way, so that the program can App Shared between. But it has to be the same TeamID
keychain Your data is encrypted

UIPasteboard
 stay iOS of UI In the system, there are three controls with cutting board operation, which are UITextField,UITextView And UIWebView. Long press gestures at the text interaction of these controls can call out the system's clipboard control on the screen view, and users can copy, paste, cut and other operations
UIPasteboard Typical usage scenarios are Taobao and wechat/QQ Link sharing.
advantage
 Universality, as long as it is necessary to identify specific identification, it can not be affected APP Impact of communication between
 shortcoming
 Manual processing is required
UIDocumentInteractionController
UIDocumentInteractionController yes OC A class of language, but it is not a class controller,But one inherited from NSObject class
1.Preview similar pdf,doc,ppt And other types of files.
2.The files received by the user can be shared with other users on the user's mobile phone App Yes.

usage method:
Create a UIDocumentInteractionController Properties of class:
follow UIDocumentInteractionControllerDelegate

1.Specify the link to share
 NSURL *URL = [[NSBundle mainBundle] URLForResource:@"ios-" withExtension:@"pdf"];      
 _document = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:cachesDir]];

2.Set up sharing agent
    _document.delegate    =  (id)self;

3.What kind of files can be opened by a third party? If you don't prove it here, it means all files!
//    _document.UTI = @"com.microsoft.word.doc";

4.Judge whether there is an application in the mobile phone that can open the file and open the sharing interface
// The user previews the file, as shown in Figure 1
//BOOL canOpen =   [_document presentPreviewAnimated:YES];
// Users can share files directly without previewing them, as shown in Figure 2
    BOOL canOpen = [self.document presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
    if(!canOpen) {
   NSLog(@"No program can open the selected file");
    }

5.As shown in Figure 2, the call is successful. Click the application you want to share.

3. When you click (perform an operation), you want to terminate the dispatch_ Execution of code blocks in after?

4. Advantages and disadvantages of single case writing and destruction method?

Advantages of singleton:
A class is instantiated only once, providing controlled access to a unique instance
 Save system resources; Variable instances are allowed.

Disadvantages of single example:
There is only one object in a class, which may cause excessive responsibility and violate the "single responsibility principle" to a certain extent; Since there is no abstraction layer in the singleton pattern, it is very difficult to expand the singleton class; Abusing singleton will bring some negative problems. For example, in order to save resources, designing database connection pool objects as singleton classes may lead to too many programs sharing connection pool objects and connection pool overflow; If the instantiated object is not used for a long time, the system will consider it as garbage and be recycled, which will lead to the loss of object state.

How to create:
+(instancetype)shareInstance{
    static SingleModel *_instance = nil;
    dispatch_once_t onceToken = nil;
    dispatch_once(&onceToken,^{
       _instance = [[super alloc] initWithZone: NULL] init];
       return _intance;
    })
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self shareInstance];
}

How to destroy:
Set object to nil
+(void)attempDealloc{
      onceToken = 0; // Only when set to 0,GCD will think it has never been executed It defaults to 0 This ensures that the object will be created again the next time shareInstance is called
      [_instance release];
    _instance = nil;
}

5. What is the relationship between the address and physical address of a process?

Process CPU,CPU The logical address recorded in the process can be accessed. If it is a page memory management scheme, the logical address includes page number and intra page offset. The page number can be queried in the page table to obtain the page frame number and page frame number divided in physical memory+CPU The base register value (the starting address of the process in memory), and then splice the offset in the previous page to get the corresponding actual physical address

6. What is the difference between serial, parallel, synchronous and asynchronous?

Parallelism: make full use of the multi-core of the computer to synchronize on multiple threads

Concurrency: fast switching on one thread makes people feel synchronized

 Synchronization: with dispatch_sync,The current thread is blocked

Asynchronous: with dispatch_async There is no blocking current thread

Serial queue: the tasks of the queue are executed in the order of first come first served.

Concurrent queue: the execution time of each task is different, and the order of all execution is also different.

7. The three tasks a-b-c are executed separately. How to control the sequence?

stay NSOperation You can easily add dependencies to make tasks execute in a specific order. oper2 addDependency oper1 At this time, task 2 will not be executed until task 1 is executed
dispatch_queue_t queue = dispatch_queue_create("wq", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"thread1");
        [NSThread sleepForTimeInterval:1.0];
    });
    dispatch_barrier_async(queue, ^{
        NSLog(@"thread2");
    });
    dispatch_async(queue, ^{
        NSLog(@"thread3");
    });

8. By default, the child thread will not start Runloop. How to deal with the Autorelease object? Is there a memory leak if you don't handle it manually?

In the sub thread, you create Pool If so, it will happen Autorelease The object will be handed over to pool To manage. If you didn't create Pool ,But there was Autorelease Object, it will call autoreleaseNoPage method. In this method, it will automatically create one for you hotpage(hotPage Can be understood as currently in use AutoreleasePoolPage,If you still don't understand, you can have a look first Autoreleasepool And call page->add(obj) Add objects to AutoreleasePoolPage In the stack, that is to say, you do not carry out manual memory management, and there will be no memory leakage!

9. Why refresh the UI only in the main thread? Why can't I update the page in an asynchronous thread? Why?

because UIKit Not thread safe. Imagine the following situations:
If two threads set the same background image at the same time, the application may crash because the current image is released twice.
Two threads set the same thread at the same time UIView The background color, then it is likely that the rendering shows the color A,And at this time UIView The background color attribute on the logical tree is B. 
Two threads operate simultaneously view Tree structure of: in thread A in for Loop through and operate the current View All subView,Then at this time, the thread B Select a subView Delete directly, which leads to confusion and may also lead to application crash. iOS4 After that, Apple will most of the drawing methods and methods, such as UIColor and UIFont Such classes can be rewritten for thread safety, but it is still strongly recommended UI The operation is guaranteed to be executed in the main thread.

10. How to keep the thread alive? And how to destroy resident threads?

Open a for the current thread RunLoop

To this RunLoop Add a port/source Such maintenance RunLoop Event loop for

Start the RunLoop

11. When does runloop start from the main thread?

12. What is the relationship between runloop and autoreleasepool?

App After startup, apple is in the main thread RunLoop Two are registered in Observer,Its callbacks are _wrapRunLoopWithAutoreleasePoolHandler(). 

first Observer The events monitored are Entry(About to enter Loop),Called within its callback _objc_autoreleasePoolPush() Create an auto release pool. his order yes-2147483647,The highest priority ensures that the creation of the release pool occurs before all other callbacks.

the second Observer Two events were monitored: BeforeWaiting(Ready to go to sleep) Time call_objc_autoreleasePoolPop() and _objc_autoreleasePoolPush() Release the old pool and create a new one; Exit(About to quit Loop) Time call _objc_autoreleasePoolPop() To release the auto release pool. this Observer of order It is 2147483647, with the lowest priority to ensure that its release pool occurs after all other callbacks.

13. How can GCD A rely on B and C rely on A?

14. Let's talk about the understanding of GCD. What are its methods and what are they used for?

15. Has GCD and Operation been used for comparison?

(1)GCD The execution efficiency is higher, and because the execution in the queue is performed by block This is a lightweight data structure, which is more convenient to write

(2)GCD Only support FIFO Queue, and NSOperationQueue You can adjust the execution order by setting the maximum concurrent number, setting the priority, adding dependencies, etc

(3)NSOperationQueue You can even set dependencies across queues, but GCD You can only set up a serial queue or add it in the queue barrier(dispatch_barrier_async)The execution order can be controlled only after the task is completed,More complex

(4)NSOperationQueue Because of object-oriented, so support KVO,Can monitor operation Is it executing( isExecuted),End( isFinished),Cancel( isCanceld)

16. The underlying thread scheduling principle of GCD?

First, the thread life cycle includes: New(create),be ready(ready),function(run),block(block), death(dead) iOS Thread management is divided into,pThread,NSThread,GCD,NSOperationpthread: POSIX Standard, based on C General cross platform thread management of language API. NSThread: Earliest apple Management thread apiNSOperation:be based on GCD Object oriented thread management ApiGCD: replace NSThread,C Thread management of language Api

GCD There is a thread pool at the bottom, which does not need to be written by developers. The threads in the thread pool have good reusability. When this thread is not called nonsense after a period of time, this thread will be destroyed. Then we just need to add tasks to the thread queue and schedule the thread queue. If synchronous tasks are stored in the queue, a thread will be provided in the underlying thread pool for the task to execute after the task is out of the queue. After the task is executed, the thread will return to the thread pool. If asynchronous tasks are stored in the queue, when the task is out of the queue, the underlying thread pool will provide a thread for task execution. Because it is asynchronous execution, the task in the queue can schedule the next task without waiting for the current task to finish executing. At this time, the underlying thread pool will provide another thread for the second task to execute, After execution, return to the underlying thread pool. In this way, the threads are reused without starting a new thread for each task execution, which saves the system overhead and improves the efficiency.

17. How is memory managed in the sub thread?

18. How to implement a thread safe array?

19. Thread priority?

20. What should be paid attention to in multithreading?

21. How to start a thread? Can the thread be canceled?

22. what is called connection in subthread? Why not callback?

Because runloop is not added, the task is destroyed after execution, so there is no callback.

23. When will the autorelease variable in the child thread be released?

When each thread is created, one is created autorelease pool,And when the thread exits, it is emptied autorelease pool. So the number of sub threads autorelease Object, or set in the child thread runloop clear

When pthread_exit Triggered when exiting_pthread_tsd_cleanup,trigger AutoreleasePoolPage of tls_dealloc(void*),Then recycle autorelease object

24. In the sub thread, do you need to add autoreleasepool?

25. Thread synchronization problem (A outputs odd number, B outputs even number, and let the two processes output in order)?

26. What is the maximum thread concurrency achieved by GCD? (use dispatch_semaphore) and manually realize the maximum concurrency of the queue?

27. Which spaces in the process are shared by threads?

28. You just said that the global variables of the process are shared. When there are multiple threads to use, is there any protection mechanism?

29. Are notifications sent and received on the same thread?

30. What are the differences between main threads and sub threads, and why?

31. Ask GCD how to suspend the task?

32. Can a single CPU realize multi task parallelism?

33. GCD implements variable reading and writing?

34. If the thread is truncated halfway, will the resources be released? What about the process?

35. Thread synchronization. Thread D needs to be executed after the execution of ABC thread. How to design?

Option 1: use group and semaphore
 Option 2: group_enter and group_leave It can also be realized

    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_group_async(group, queue, ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //Asynchronous execution A
            dispatch_semaphore_signal(semaphore);
        });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });

    dispatch_group_async(group, queue, ^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             //Asynchronous execution B
            dispatch_semaphore_signal(semaphore);
        });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });

    dispatch_group_async(group, queue, ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             //Asynchronous execution C
            dispatch_semaphore_signal(semaphore);
        });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });

    dispatch_group_notify(group, queue, ^{
             //Executive D
    });

36. What is the use of GCD semaphores other than synchronization?

37. What are the uses of signal(), wait()?

38. Thread synchronization method?

39. Memory distribution of processes?

40. What operations are required for thread switching?

41. Is it better to have more threads? What's the harm of too many threads?

42. How to realize synchronous reading and asynchronous writing for a variable?

43. How to send 10 network requests and then perform subsequent operations after receiving all responses?

GCD Semaphore, queue group

Practice: adopted dispatch_group_t To implement, put each request into Group In, the operation of merging into a large picture is placed in dispatch_group_notify Implemented in.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{ /*Load picture 1 /});

dispatch_group_async(group, queue, ^{ /Load picture 2 /});

dispatch_group_async(group, queue, ^{ /Load picture 3 */ });

dispatch_group_notify(group, dispatch_get_main_queue(), ^{

// Merge pictures

});

dispatch_group_enter()and dispatch_group_leave()

44. Give you a static variable int i=0, and then the for loop executes 20 threads. I + + is executed in each thread. Ask the value of I after execution?

45. What is the status of the process? How many states of threads?

46. Five processes read a file. How can only two processes read the file at the same time?

47. In depth understanding of dispatch_sync and dispatch_async?

「dispatch_sync Distributed block The execution thread of is always the same as dispatch_sync The context is the same thread」

dispatch_suspend(dispatchA);

Will only pause dispatchA On the original block The execution of, dispatchB of block Will not be affected. And if you pause dispatchB Will be suspended dispatchA Operation of.

48. Does the code executed in GCD queue and main queue must be in main thread?

about queue The code executed in is not necessarily main thread Yes. If queue If it is created in the main thread, the executed code is executed in the main thread

that 's ok. If it is created in a child thread, it will not be created in main thread Execute in.

 about main queue It is in the main thread, so it must be executed in the main thread. obtain main queue It's OK. We don't need to create it. The way to get it is common

Over call method dispatchgetmain_queue To get it.

49. What are the algorithms for thread scheduling and when are they used?

50. What are the two types of GCD queues?

51. How to synchronize several asynchronous calls with GCD?

Use the scheduling group to add blocks to the global group queue. If all these blocks are executed, the blocks that end processing in the main scheduling queue will be executed.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,queue,^ { / *Load picture 1 * / });
dispatch_group_async(group,queue,^ { / *Load picture 2 * / });
dispatch_group_async(group,queue,^ { / *Load picture 3 * / }); 
dispatch_group_notify(group,dispatch_get_main_queue(),^ {

        //Merge pictures

});

52. dispatch_ barrier_ What is the function of async?

It can solve the problem of multiple reading and single writing

In the concurrency level, in order to maintain the order of some tasks, you need to wait for some tasks to complete before continuing. Use barrier To wait for the task to complete and avoid data dispatch_barrier_async Competition and other issues. The function will wait until the concurrent scheduling queue is fully executed, and then execute dispatch_barrier_async Processing of function addition, etc dispatch_barrier_async After the execution of the additional processing, the concurrent scheduling queue will resume and the previous actions will continue to be executed.

For example: when your company travels with a group on weekends and goes to the high-speed rest station, the driver says: everyone goes to the toilet, make a quick decision, and go to the high-speed after going to the toilet. The oversized public toilet is where everyone goes at the same time. The program ape will soon end, but the program Yuanyuan may be slower. Even if you come back first, the driver won't start. The driver can't start until everyone comes back. dispatch_barrier_async The additional content of the function is like the action of "going to the highway after going to the toilet".

53. Why did Apple abandon dispatch_get_current_queue?

dispatch_get_current_queue Since the distribution model is organized hierarchically, this means that the blocks in a series will be executed in their superior series. Whether the queue is the queue used to perform synchronous dispatch is not always effective. dispatch_get_current_queue Function is usually used to solve the deadlock caused by non reentrant code, and then the problem that can be solved by this function can also be solved by "specific data".

54. Have you ever done asynchronous network processing and communication? If yes, can you introduce some implementation strategies in detail?

55. Is the attribute used by the Block in GCD required__ weak modification?

no

56. Default value of maxConcurrentOperationCount in nsoperationqueue?

57. Does asynchrony always start a new thread?

58. By default, the child thread will not start Runloop. How to deal with the Autorelease object? Is there a memory leak if you don't handle it manually?

In the sub thread, you create Pool If so, it will happen Autorelease The object will be handed over to pool To manage. If you didn't create Pool ,But there was Autorelease Object, it will call autoreleaseNoPage method. In this method, it will automatically create one for you hotpage(hotPage Can be understood as currently in use AutoreleasePoolPage,If you still don't understand, you can have a look first Autoreleasepool And call page->add(obj)Add objects to AutoreleasePoolPage In the stack, that is to say, you do not carry out manual memory management, and there will be no memory leakage!

59. How does the system remove an NSOperation with isFinished=YES?

Through KVO;

60. With threads, why do you think there should be runloop?

Runloop The main function is how it sleeps when there is no message processing and wakes up when there is a message. This can improve CPU Resource efficiency. runloop Another function is message processing. Only threads can't do this.

61. PerformSelector:afterDelay: does this method work in the child thread?

It doesn't work. The child thread doesn't work by default Runloop.  When called NSObject of performSelecter:afterDelay: After that, it will actually create one inside Timer And added to the current thread RunLoop Yes. So if the current thread does not RunLoop,Then this method will fail. have access to GCD of dispatch_after To achieve afterDelay Such demand.

When called performSelector:onThread: When, it actually creates a Timer Add to the corresponding thread. Similarly, if the corresponding thread does not RunLoop This method will also fail,

62. Two processes point to the same address space and initialize a value. What are the outputs respectively?

63. Is the Block in GCD on the heap or stack?

64. Why does the main thread execute deadlock synchronously?

65. How do I terminate a running worker thread?

66. How to implement a thread pool with a specified number of threads under IOS?

67. Why use dispatch for a single case_ once_ t?

dispatch_once Principle of:

dispatch_once Mainly based on onceToken To determine how to execute the code.

1.When onceToken= 0 When, the thread executes dispatch_once of block Medium code

2.When onceToken= -1 Thread skips when dispatch_once of block Code in does not execute

3.When onceToken For other values, the thread is blocked and waits onceToken Value change

When a thread calls shareInstance,here onceToken= 0,call block Code in, at this time onceToken The value of becomes 768. When another thread calls shareInstance Method, onceToken The value of is already 768. The thread is blocked. When block Thread execution completed block After that, onceToken Become-1.Other threads are no longer blocked. Skip block. Call again next time shareInstance When, block Already for-1.Skip directly block. 

68. Say the results printed by GCD thread below

//Demo: execution order

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"1");
    });
    NSLog(@"2");
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0);
    dispatch_sync(queue, ^{
        NSLog(@"3");
    });
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"4");
    });
    dispatch_async(queue, ^{
        NSLog(@"5");
    });
    NSLog(@"6");
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:0];
    NSLog(@"8");
}
- (void)delayMethod {
    NSLog(@"7");
}

Print result: 23658147; Among them, 5 and 8 are exchanged randomly

69. How to realize dispatch once and what issues should be considered?

70.

Topics: Interview