Block of code and concurrency

Source: Internet
Author: User

Code block object:

Usually called: code block, is the extension of the C language, in addition to the code in the function, its harm contains variable binding. Code blocks are sometimes referred to as closures (closure). Two types of bindings: automatic and managed. The automatic type uses the memory in the stack, and the managed bindings are created from the heap.

Code blocks and function pointers:

Code block features: 1. The return type can be either manually declared or deduced by the compiler. 2. A list of parameters with the specified type. 3. Useful name.

Declares a function pointer:void (*my_func) (void); This is a very basic function pointer, it has no parameters and return results, as long as the * replaced by ^ can be converted to a code block definition. such as:Void (^my_block) (void);

Use the power operator at the beginning of both the declaration code block variable and the code block implementation. As in the function, the code block is placed in {}.

Int (^square_block) (int number) = ^ (int number) {return (number * number);};

int result = Square_block (5); printf ("result =%d \ n", result);

This particular block of code takes a shape parameter and returns the square of the number, preceded by the definition of a block of code, followed by the implementation of the equals sign.

General expression:<returntype> (^blockname) (list of arguments) = ^ (arguments) {body;};

Typdef

TYPEDF double (^mksamplemultiply2blockref) (double C, double D);

This line of code defines a code block variable named Mksamplemultiply2blockref that contains two double floating-point parameters and returns a double-floating-point value.

Mksamplemultiply2blockref multiply2 =^ (double C, double D) {return c * D;};

printf ("%f,%f", multply2 (4,5), Multply2 (5, 2));

Local variables

A local variable is a variable declared within the same scope as the code block.

typedef Double (^mksample) (void);

double a = ten , B = +; // Local Variables

mksample multiply = ^ () { return A * b;};

NSLog (@ "%f", Multiply ()); // The result is $

A = ; b = ;

NSLog (@ "%f", Multiply ()); // The result is still $

Parameter variables

parameter variables in a code block have the same effect as parameter variables in a function.

_block variable

local constants are obtained by code blocks as constants, and if you want to modify their values, you must declare them as modifiable, for example: double c = 3; Mksample Multiply = ^ (double a,double b) { return A * b;}; At this point the compiler will make an error. c should be declared as _block double c =3;

Two limitations of the _block type: There is no variable-length array, and there is no struct with a variable-length array. Both of these variables cannot be declared as _block types.

Local variables inside the code block

These variables have the same effect as local variables in the function.

Objective-c variable

If a OC object is referenced, it must be preserved, and if an instance variable is accessed by reference, the self (the Execution method object) is preserved once, and the variable needs to be persisted by a numeric access to an instance variable.

Because a block of code is an object, you can send him any messages related to memory management. In the C language level, you must use the Block_copy () and block_release () functions to properly manage memory.

Concurrency:

If you just want some code to run in the background, NSObject provides methods, and these methods have performselector in their names: The simplest is: performselectorinbackground:withobject:; He can execute a method in the background by creating a process to run the method.

These methods cannot have return values, and either have no arguments or have only one parameter object. Only one of the following code formats can be used:

-(void) MyMethod; -(void) MyMethod: (ID) myObject;

The code we should implement is as follows:

-(void) mybackgroudmethod{

@autoreleasepool

{

NSLog (@ "My Background Method.");

}

Or

-(void) Mybackgroudmethod: (ID) myobject{

@autoreleasepool

{

NSLog (@ "My Background Method.");

}

}

If you want to execute your method in the background, simply call performselectorinbackground:withobject:;

[ self performselectorinbackground: @selector (mybackgroudmethod) Withobject:nil];

Scheduling queue:

Continuous queue: dispatch_queue_t my_serial_queue;

My_serial_queue = Dispatch_queue_create ("compares. MySerialQueue1 ", NULL);

The first parameter is the name of the queue, and the second is the attribute that is responsible for providing the queue, which is now null.

If you want to change the priority, you can call the Dispatch_get_global_queue method.

Three priority levels: Dispatch_queue_priority_high

Dispatch_queue_priority_low

Dispatch_queue_priority_defalut.

Use Dispatch_get_main_queue to access contiguous queues related to the main thread of the application.

The dispatch queue is a reference count object, and you can modify the value of the counter with Dispatch_retain () and Dispatch_release ().

About cleanup functions: Let the object call a function when it is deprecated, just like the Dealloc function in a class.

void function_name (void *context);

void Myfinalizer (Viod *content) {

NSLog (@ "myfinalizerfunction.");

Nsmutabledictionary *thedata = (__bridge_transfer nsmutabledictionary*) context;

[Thedata removeallobjects];

}//This function is also called a finalizer function

The __bridge_transfer keyword is to transform the memory management of an object from a global free pool into our function.

The __bridge keyword is to tell arc that we do not manage context content ourselves and leave it to the system to manage it.

Scheduler:

The simplest way to add a task is through a block of code, which must be a type such as dispatch_block_t, which is defined as having no parameters and a return value. For example: typedef void (^dispatch_block_t) (void).

Add the Async code block first, which has two parameters: Queue and code block.

Dispatch_async (_serial_queue,^{NSLog (@ "serial Task 1");

If you want to add synchronously, use the Dispatch_sync function. Function prototype: void function_name (void *argument)

and other follow-up ~~~~~~~~~

The pace of the recent course has been accelerating a lot, and the foundation is too weak to learn very hard//

Block of code and concurrency

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.