How does the Communist Party work?

This paper included: https://juejin.cn/post/6976878024566243335

1. Serial queue, synchronous operation, no new thread is created, operation is executed sequentially; Serial queue, asynchronous operation, will create a new thread, the operation sequence, using the scenario: neither affect the main thread, but also need to execute the operation sequence;

2. Parallel queue, synchronous operation, no new county, operation sequence; Parallel queue, asynchronous operation, will create a new thread, the operation is carried out out of order, if there are other tasks in front of the queue, it will wait for the execution of other tasks;

The global queue is systematic, so you can get it directly and the UI update has to be done on the main thread,

Global queue asynchronous operation, will create a new child thread, the operation is executed out of order, if there are other tasks before the queue, will wait for the execution of other tasks in the call;

All operations are executed in the main thread sequence. There is no concept of asynchrony. Synchronized operations added to the main queue will never be executed

The singleton pattern

AllocWithZone is the method that will eventually be called when an object allocates memory space, override this method to make sure that only one piece of memory is allocated dispatch_once is thread-safe, and that the contents of the block code are executed only once

Synchronization operations added to the serial queue are deadlocked, but the code preceding the nested synchronization operation is executed.

Synchronous operations added to parallel queues do not deadlock on the main thread;

Synchronized operations added to the global queue do not deadlock.

The main purpose of synchronous operation is to block the execution of parallel queued tasks. The following tasks will not be executed until the current synchronous task is completed. Application: user logs in

The difference between queues and threads:

Queue: manages threads, which is equivalent to a thread pool, and manages when threads execute.

Queues are divided into serial queues and parallel queues

Serial queue: The threads in the queue execute sequentially (not simultaneously)

Parallel Queue: Threads in the queue execute concurrently. There may be a question, is the queue first in first out? If the following tasks are finished, how can they get out? It is important to emphasize that the task is not necessarily out of the queue when it has finished executing. Only after the execution of the previous task, you will be out of the queue, that is to say, even if you have finished executing, you must wait until the execution of the previous task is finished and out of the queue, then you can go out.

There is also a difference between the main thread queue and the queue created by the GCD.

The main thread queue is different from the queue created by the GCD.

Queues created in the GCD have lower priority than the main queue, so if a synchronous task is not nested in a serial queue in the GCD, it will not block the main thread. There is only one way to cause a deadlock, that is, if a synchronous task is nested in a serial queue, it will cause a deadlock.

Synchronization cannot be enabled in the main thread queue and will block the main thread.

Asynchronous tasks can only be started. Starting an asynchronous task does not start a new thread. It is only called when the priority of the asynchronous task is lowered and the CPU is free. Synchronous tasks, on the other hand, preempt the resources of the main thread, causing a deadlock.

Threads: There are many tasks (synchronous, asynchronous)

The difference between synchronous and asynchronous:

Synchronized tasks have high priority, have an order of execution in the thread, and do not start a new thread.

Asynchronous tasks have low priority and are executed out of order in the thread, depending on the CPU.

No new threads are started in the main queue; other queues start new threads.

Main thread queue note:

  • The following code is executed in order
  •  1111
  •  2222

The main queue is asynchronous

<NSThread: 0x8e12690>{name = (null), num = 1}

Starting an asynchronous task in the main queue does not start a new thread but still executes the code in the block in the main thread. Why aren’t threads blocked?

The main queue starts an asynchronous task. It doesn’t start a new thread, but it lowers the priority of the asynchronous task and, at a later time, executes the asynchronous task on the main thread.

Synchronized tasks are started in the main queue. Why are threads blocked?

Start a synchronous task in the main queue. Because the main queue is a serial queue, the threads in the main queue are in order. One thread is executed before the next thread is executed, but the main queue always has one main thread. So if you start a synchronous task on the main thread, the synchronous task will want to preempt the executing resources, while the main thread is doing something and won’t let go. Both are high priority, resulting in deadlocks that block the thread.

- (void)main_queue_deadlock { dispatch_queue_t q = dispatch_get_main_queue(); NSLog(@"1111"); Dispatch_async (q, ^{NSLog(@" main queue async %@", [NSThread currentThread]); }); NSLog(@"2222"); // dispatch_sync(q, ^{// NSLog(@" main queue synchronization %@", [NSThread currentThread]); / /}); }
In parallel queue, synchronous tasks are executed in order, only asynchronous tasks are not executed in order.
Serial queues start asynchronous tasks sequentially
Nesting synchronous tasks after asynchronous tasks are started by serial queue causes a deadlock
- (void)serial_queue_deadlock2 { dispatch_queue_t q = dispatch_queue_create("cn.itcast.gcddemo", DISPATCH_QUEUE_SERIAL); Dispatch_async (q, ^{NSLog(@" asynchronous task %@", [NSThread currentThread]); // If the thread in the serial queue is executed sequentially, the asynchronous task will not be executed until the async task is completed. If the asynchronous task above is not finished until the curly brace below, and the synchronous task below is preempting resources, a deadlock will occur. Dispatch_sync (q, ^{NSLog(@" Sync task %@", [NSThread currentThread]); }); });
Nested synchronous tasks cause a deadlock after a synchronous task is started by a serial queue
- (void)serial_queue_deadlock1 { dispatch_queue_t q = dispatch_queue_create("cn.itcast.gcddemo", DISPATCH_QUEUE_SERIAL); Dispatch_sync (q, ^{NSLog(@" Sync task %@", [NSThread currentThread]); // If the thread in the serial queue is in a sequence of execution, the synchronization task will not be executed until the synchronization task is completed. If the synchronization task above is not finished until the curly brace below is closed, and the synchronization task below is preempting resources, a deadlock will occur. Dispatch_sync (q, ^{NSLog(@" Sync task %@", [NSThread currentThread]); }); }); NSLog(@" Synchronize task %@", [NSThread currentThread]); } Nesting asynchronous tasks after synchronous tasks are started by serial queue does not cause deadlock

Network:

PUT method

Put 1) unlimited file size 2) can overwrite files

2M 2) Create a new file and do not repeat the same name

Base 64 is the most commonly used encoding format for network transmissions – the encoding used to encode binary data into strings

Usage of BASE 64:

> can encode, can decode


> is used as the base algorithm by many encryption algorithms

Audio processing

Dependent frameworks: AVFoundation, AudioToolbox framework

Play long music: AVAudioPlayer

Play short sound effects: Load audio files to generate SystemSoundId

Recording: AVAudioRecord

Low level, advanced audio/video processing

CoreAudio, CoreVideo framework

How XMPP works

The node connects to the server

The server authenticates it with a certificate in the local directory system

The node specifies the destination address and lets the server tell the destination status

The servers look up, connect, and authenticate each other

The nodes interact with each other

The main extension functionality provided by the XMPP framework

XMPPreconnect: Automatically reconnect the XMPP stream if it is unexpectedly interrupted

XMPProster: The standard XMPP roster

Xmpproom: Support for multiplayer chat

XMPPPubSub: Provides public subscription support

Communication categories and public XML attributes

Real-time messaging systems using XMPP include three major categories of communication:

Message passing, in which data is transferred between interested parties

Online status, which allows users to broadcast their online status and availability

Information/query requests, which allow an XMPP entity to make a request and receive a response from another entity

All three types of XMPP sections have the following common attributes:

From: The JID of the source XMPP entity

To: The JID of the intended recipient

Id: Optional identifier for the current conversation

Type: An optional subtype of the section

XML :lang: A description of the language of the message if the content is human-readable

XMPP core file

XMPPStream: This is the primary interaction class for development, and all extension and custom code is based on this class

XMPPParser: Used for XMPPStream parsing

XMPPJID: Provides an implementation of an immutable JID that complies with the nScopying and nScoding protocols

XMPPElement: The base class for the following three XMPP elements

XMPPIQ: request

XMPPMessage: message

XMPPPresence: attend

XMPPModule: Used when developing XMPP extensions

XMPPLogging: The logging framework for XMPP

XMPPInternal: The core and high-level low-level content used internally by the entire XMPP framework

XMPP frameworks often use extensions

XEP-0045: Multi-user chat

XEP-0060: Publish-subscribe

XEP-0065: SOCKS5 byte stream

XEP-0085: Chat status notification

XEP-0096: File transfer

XEP-0172: User nickname

XEP-0184: Message delivery

CoreDataStorage: Data storage

Reconnect: Reconnect

Roster: Roster

The XMPP column frame

CocoalumBerjack: Logging framework

CocoaAsyncSocket: The underlying network framework to achieve asynchronous Socket network communication

You need to add a CFNetwork&Security framework dependency

KissXML: An XML parsing framework

You need to add the libxml2.dylib framework dependency

You need to specify the following compilation options:
OTHER_LDFLAGS = -lxml2
HEADER_SEARCH_PATHS = /usr/include/libxml2
libidn

Difference between global and parallel queues

dispatch_queue_t q =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

1> does not need to be created, directly GET can be used

2> Both queues execute equally

3> global queue has no name. When debugging, the exact queue cannot be confirmed

> global queue has high default priority

Parallel lines

`dispatch_queue_t q = dispatch_queue_create(“ftxbird”, DISPATCH_QUEUE_CONCURRENT); `

Serial queues

dispatch_queue_t t = dispatch_queue_create("ftxbird",DISPATCH_QUEUE_SERIAL);

In development, trace the current thread

[NSThread currentThread]

Examples of task nesting for parallel queues

 

dispatch_queue_t q = dispatch_queue_create("ftxbird", DISPATCH_QUEUE_CONCURRENT); Dispatch_sync (q, ^{NSLog(@" 1%@ ", [NSThread currentThread]); dispatch_sync(q, ^{ NSLog(@"2 %@", [NSThread currentThread]); dispatch_sync(q, ^{ NSLog(@"3 %@", [NSThread currentThread]); }); }); dispatch_async(q, ^{ NSLog(@"4 %@", [NSThread currentThread]); }); NSLog(@"5 %@", [NSThread currentThread]); });

Main queue (thread)

1> There is only one main thread per application

> All UI updates must be performed on the main thread!

3> The main thread is always working, and it never ends until the program is killed! dispatch_queue_t q = dispatch_get_main_queue();

Example of updating the UI on the main queue

Void (^TaskOne)(void) = ^(void) {NSLog(@"Current Thread = %@", [NSThread currentThread]); NSLog(@"Main thread = %@", [NSThread mainThread]); [[[UIAlertView alloc] initWithTitle:@"GCD" message:@"Great Center Dispatcher" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show]; }; Dispatch_queue_t mainQueue = dispatch_get_main_queue(); // Submit the task dispatch_async(mainQueue, TaskOne); } // async(dispatch_get_main_queue(), ^(void) {NSLog(@"Current thread = %@", [NSthread currentThread]); NSLog(@"Main thread = %@", [NSThread mainThread]); [[[UIAlertView alloc] initWithTitle:@"GCD" message:@"Great Center Dispatcher" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show]; });

NSOperation multithreading technology

NSBlockOperation is easy to use

@property (nonatomic, strong) NSOperationQueue *myQueue; self.myQueue = [[NSOperationQueue alloc] init];

1> in custom queue

NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"%@", [NSThread currentThread]);}];

All custom queues are run in child threads.

[self.myQueue addOperation:block];

Or:

[self.myQueue addOperationWithBlock:^{NSLog(@"%@", [NSThread currentThread]);}];

2> is executed in the main queue

[[NSOperationQueue mainQueue] addOperationWithBlock:^{NSLog(@"%@", [NSThread currentThread]);}];

NSInvocationOperation is easy to use

 NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demoOp:) object:@"hello op"];

- (void)demoOp:(id)obj
{
    NSLog(@"%@ - %@", [NSThread currentThread], obj);
}

Use performSelectorOnMainThread method

[NSthread sleepForTimeInterval:1.0]; / / 2 > set up the image, apple allows the use of bottom performSelectorInBackground method / / update the UI thread in the background, strongly recommended not to do so! // No does not block the thread until the method is called. Will continue to perform [self performSelectorOnMainThread: @ the selector (setImage:) withObject: [UIImage imageNamed: imagePath] waitUntilDone:NO]; // 1. Image - (void)setImage:(UIImage *)image {self.imageView.image = image; [self.imageView sizeToFit]; }

Question: What’s wrong with the code? What happens if the number of loops is very large? How should it be modified?

   

@autoreleasepool for (int I = 0, int I = 0, int I = 0, int I = 0; i < 10000000; ++i) { @autoreleasepool { // * NSString *str = @"Hello World!" ; // new * str = [str uppercaseString]; // new * str = [NSString stringWithFormat:@"%@ %d", str, i]; NSLog(@"%@", str); }}

Recommended at the end of the article: iOS popular collection & video analysis

1) Swift

② The underlying technology of iOS

③iOS reverse protection

④iOS interview collection

⑤ big factory interview questions + underlying technology + reverse security + SWIFT