IOS concurrent programming (1) -- thread

Source: Internet
Author: User
So far, your iOS code has only one mainthread, and your program has always been serial. You have always finished task a and then Task B, even if there is no dependency between AB. Mainthread is used to process UI-related events. If you execute some tasks that require a lot of time (such as downloading data from the network) in mainthread ), the user experience of this program will be very poor, because users often need to wait for a long time. Important: any UI-related operations should be handled in mainthread.At the same time, you need to know that all mobile devices are named as multi-core devices. Do you mean that your programs only occupy one of them, while others are all self-occupied ?! I don't think it is necessary for me to explain what advantages multi-thread programming has and what benefits it will bring, because everyone knows. Of course, to achieve program concurrency, and do not require that the device running it must be multi-core, we can schedule the CPU (time slice rotation) to achieve simultaneous execution of the "show above. Before starting this article, it is necessary to explain several key terms: thread, which can be simply understood as a code segment that can be executed independently. Process: A running executable program. A process can contain multiple threads. Task: the abstraction of the work executed by the program. Concurrency (concurrency)-indicates that a program can execute multiple tasks at the same time or almost simultaneously.
As mentioned above, program concurrency can be realized even with single-core CPU. For example, if 10 tasks with the same priority need to be executed within 1 s, the system can divide the CPU time of 1 s into 10 100 ms, and allocate the 10 ms CPU time to 10 tasks. On the surface, the 10 tasks are executed simultaneously within 1 s of CPU time. However, the current system has implemented a real multi-core architecture, and there is no need to shard time slices on a CPU. Besides, CPU scheduling also consumes resources and time. 1.1 using threads to implement concurrency in IOS would be an unprecedented simplicity. The most direct:
[self performSelectorInBackground:@selector(try:) withObject:para1];
Simply call the functions mselectorinbackground: withobject: function, and pass the function (task) You want to execute concurrently to the first parameter, such as try in the example. The second parameter para1 is the parameter of the try function. In this way, the system automatically opens up a background thread for you. Your task is already in the background rather than mainthread. You can also manually create a new thread as follows:
[NSThread detachNewThreadSelector:@selector(try:)  toTarget:self withObject:para1]
This is a class method. You can also create a thread instance:
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMainMethod:)  object:nil];//start thread manually[myThread start];

To prevent memory leakage, if you are using a memory management model (including retain and release operations), you should add autoreleasepool in try, as shown in the main function:

-(void)try:(id)para1{    @autoreleasepool{                /*do something here*/    }}

You should do the same when calling the background thread. There is no substantial difference between the two methods. If you are using the garbage collection mechanism (ARC), The created Auto Release pool will be ignored, but it is harmless.

If you have created multiple thread instances, you can use:

performSelector:onThread:withObject:waitUntilDone:

Method to call them to execute the corresponding task. You can also configure the created thread instance. 1.1.1 The system allocates a part of the memory space in the process space for every thread you create in the program. The stack manages the data of the thread, for example, all the local variables in the thread will be in the stack. You can call the following functions to configure and access the thread Stack:
- (NSUInteger)stackSize NS_AVAILABLE(10_5, 2_0);- (void)setStackSize:(NSUInteger)s NS_AVAILABLE(10_5, 2_0);+ (NSArray *)callStackReturnAddresses NS_AVAILABLE(10_5, 2_0);+ (NSArray *)callStackSymbols NS_AVAILABLE(10_6, 4_0);
1.1.2 thread key-value dictionary each thread maintains a key-value dictionary, which stores some state information about the thread, dictionary can be accessed at any time during thread running. You can use the threaddictionary method of nsthread to obtain an nsmutabledictionary object and add the key-value pairs required by the thread.
- (NSMutableDictionary *)threadDictionary;
1.1.3 thread running status

Configure when the thread runs, when it exits, and the current running status of the thread. Let the thread sleep for a period of time and then run automatically:

+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
Cancel thread execution, start thread, and exit thread:
- (void)cancel NS_AVAILABLE(10_5, 2_0);- (void)start NS_AVAILABLE(10_5, 2_0);+ (void)exit;

Query the thread status:

- (BOOL)isExecuting NS_AVAILABLE(10_5, 2_0);- (BOOL)isFinished NS_AVAILABLE(10_5, 2_0);- (BOOL)isCancelled NS_AVAILABLE(10_5, 2_0);

1.1.4 priority

By default, the priority of the new thread is the same as that of the current thread. When the kernel scheduling algorithm determines the thread to run, the priority of the thread is taken as a consideration. A thread with a higher priority has more running opportunities. You can use:

//class method+ (double)threadPriority;+ (BOOL)setThreadPriority:(double)p;//instance method- (double)threadPriority NS_AVAILABLE(10_6, 4_0);- (void)setThreadPriority:(double)p NS_AVAILABLE(10_6, 4_0);

To set the thread priority.

Important: putting your thread at the default priority is a good choice. Increase the priority of some threads and possibly increase the hunger of some lower-priority threads. If your applications contain high-priority and low-priority threads that must interact with each other, hunger with a lower-priority State may block other threads and cause performance bottlenecks.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.