Multithreading in objective c
Before you going into the depth of objective c programming you need to read my previous tutorial click here: Learn Objective C
Thread: It is general execution of program by processor.Program can be any type like Processing of TableView in IOS,Processing of data,uploading of image etc.
In IOS there is main thread where all programs are executed.
But think that what happen if you load data from internet,it taking more time .Gnerally it Depends upon your network.If you have lowest speed of network then data takes more time to load it and the user interface behind that data will not shown until data is not loaded so main thread gets busy for solving Data rather then Showing User Interface.
So the user who uses your application can not get satification and your application marketing response goes down.It requires to make the new thread for loading data and Separates it from main thread and running in background.
MultiThreading: Multithread means different threads are running simultaneously main thread is running and other threads are running also in background so user interface do not have to wait for load data.
You think Processor is one how it running simultaneously.In general Threads are not running simultaneously it is the work of Operating System(Manage hardware and software) in our case it Is IOS which make time interval between execution of these threads.
IOS divide the times at system level for each thread.
In multiprocessor system these can run simultaneously but I will not go into detail.
In IOS how to do multithreading?
As you already know about queue. Queue are the main factor working behind the scene of multithreading.
For making good and responsive application the User Interface is only included in main thread and data related work is included in other thread.
I said you it is the queue who work behind that thread. So Queue , is line in which number of person are standing which will process first who comes first.
In Objective C programming A queue is line of blocks. Main queue contain all UI elements.Also other queue contains some data related elements.
Execute block in other queue;
Dispatch_queue_t queue=;
Dispatch_async(queue,^{});
Create other queue
Dispatch_queue_t que=Dispatch_queue_create(“name”,null);
//name is name of queue in cost char * form and null is about serial queue and concurrent queues.
Call method in main queue
-(void)performselectorOnMainThread:(sel)amethod withobject:(id)obj waituntildone:(bool)wailuntildone;
Dispatch_async(dispatch_get_main_queue(),^{});
you think why use thread?
In general we do thread base programming only at work through system level for faster execution.
In thread base program like in C programming there are memory for program and heap. It include all the instructions to executed the current processes. In IOS There is by default main thread.
You can create multiple thread and arrange in queue or execute work then call from main queue when all work is done in other blocks.
What are blocks? You can read from here:Blocks in Objective C
Method and parameter local to other thread is seen by only that thread or queue. And object created in heap is visible to all threads.
You can seen how the objects is added to heap.
Click here:object oriented programming
In IOS the time period for loading view is managed in MS (milliseconds) if the system exceed that time display gets blown.
In Objective C there are total three queues.
1.) Main Queue: process provided to this queue will run in main thread of application.
Code to work with main queue?
dispatch_get_main_queue() function.
All these function are made at low API.
2.)private queues: you can make your own queue.
Dispatch_queue_t privatequeue=Dispatch_queue_create(“name of private queue”,null);
Here first parameter is name of queue and second parameter is serial or parallel about queue. If queue is serial then all processes in block run one at a time.
otherwise run all at same time in a queue.
If you create queue privatelly then you need to release it for free up memory space.
dispatch_release(name of private queue).
But in main queue you do not worried about free up it will automatically close when application is close or view is loaded.
For submit any process to queue(any main or private) the method dispatch_async() is called.
dispatch_async(nameof queue,^{//block to executed});
3.)Global Queue: Global queue are also work throughout all project running parallely.
Dispatch_get_global_queue(); method is provided.
Dispatch_get_global_queue(Dispatch_queue_priority_background);
There are some types of global queue in Objective c used accordingly most probably background queue is used.
it works only at priority level.
View is loaded in Main thread only so some time need to work with main thread after loading other thread to call main thread.
you can nested the dispatching of pocess in private queue block.
dispatch_aync(privatequeue.^{
//any background process.
dispatch_get_main_queue(),^{
//Loading view call is here.
}
})
Ok lets we come through GCD approach.
Do you know that who manages all thread like activity in above thread management.
It is the API at low level of like C programming language. GCD is that one who manages all concurrency control activity in objective c. We go through GCD in depth in my next tutorial.
Now look through example.
In my below example if you already familiar with IOS application development then you can easily remember it but if you have not then it is difficult for you to learn MVC.But Do not be upset We will Start programming in IOS very soon.
In ViewController.h
@property (weak, nonatomic) IBOutlet UILabel *StudentName;
- (IBAction)PrintNameWithMain:(id)sender;
- (IBAction)PrintNameWithBackground:(id)sender;
- (IBAction)Update:(id)sender;
In ViewController.m
- (IBAction)PrintNameWithMain:(id)sender{
for(int i=0;i<10000;i++)
{
NSLog(@"The name of Student is printed as %d times",i);
}
self.StudentName.text=@"abc";
}
- (IBAction)PrintNameWithBackground:(id)sender {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
for(int i=0;i<10000;i++)
{
NSLog(@"The name of Student is printed as %d times",i);
}
dispatch_async(dispatch_get_main_queue(), ^{
self.StudentName.text=@"abc";});
});
}
- (IBAction)Update:(id)sender {
self.StudentName.text=@"suraj";
}
In Storyboard
As you run the application you have seen that when you click on main thread then check on Xcode console you find that loop is executed and if you click on update button on that time it will not work and what happen if you delay for 10 second in each time execution of loop. it show like below.
Now click on background thread you have seen in Xcode loop is executed at background but you can also run update button and when loop is executed it run the application.
Source code available here:Download here
I hope you like my tutorial .If you find any query you can comment here and mail me.
My next tutorial about download image from internet in other thread.
Before you going into the depth of objective c programming you need to read my previous tutorial click here: Learn Objective C
Thread: It is general execution of program by processor.Program can be any type like Processing of TableView in IOS,Processing of data,uploading of image etc.
In IOS there is main thread where all programs are executed.
But think that what happen if you load data from internet,it taking more time .Gnerally it Depends upon your network.If you have lowest speed of network then data takes more time to load it and the user interface behind that data will not shown until data is not loaded so main thread gets busy for solving Data rather then Showing User Interface.
So the user who uses your application can not get satification and your application marketing response goes down.It requires to make the new thread for loading data and Separates it from main thread and running in background.
MultiThreading: Multithread means different threads are running simultaneously main thread is running and other threads are running also in background so user interface do not have to wait for load data.
You think Processor is one how it running simultaneously.In general Threads are not running simultaneously it is the work of Operating System(Manage hardware and software) in our case it Is IOS which make time interval between execution of these threads.
IOS divide the times at system level for each thread.
In multiprocessor system these can run simultaneously but I will not go into detail.
In IOS how to do multithreading?
As you already know about queue. Queue are the main factor working behind the scene of multithreading.
For making good and responsive application the User Interface is only included in main thread and data related work is included in other thread.
I said you it is the queue who work behind that thread. So Queue , is line in which number of person are standing which will process first who comes first.
In Objective C programming A queue is line of blocks. Main queue contain all UI elements.Also other queue contains some data related elements.
Execute block in other queue;
Dispatch_queue_t queue=;
Dispatch_async(queue,^{});
Create other queue
Dispatch_queue_t que=Dispatch_queue_create(“name”,null);
//name is name of queue in cost char * form and null is about serial queue and concurrent queues.
Call method in main queue
-(void)performselectorOnMainThread:(sel)amethod withobject:(id)obj waituntildone:(bool)wailuntildone;
Dispatch_async(dispatch_get_main_queue(),^{});
you think why use thread?
In general we do thread base programming only at work through system level for faster execution.
In thread base program like in C programming there are memory for program and heap. It include all the instructions to executed the current processes. In IOS There is by default main thread.
You can create multiple thread and arrange in queue or execute work then call from main queue when all work is done in other blocks.
What are blocks? You can read from here:Blocks in Objective C
Method and parameter local to other thread is seen by only that thread or queue. And object created in heap is visible to all threads.
You can seen how the objects is added to heap.
Click here:object oriented programming
In IOS the time period for loading view is managed in MS (milliseconds) if the system exceed that time display gets blown.
In Objective C there are total three queues.
1.) Main Queue: process provided to this queue will run in main thread of application.
Code to work with main queue?
dispatch_get_main_queue() function.
All these function are made at low API.
2.)private queues: you can make your own queue.
Dispatch_queue_t privatequeue=Dispatch_queue_create(“name of private queue”,null);
Here first parameter is name of queue and second parameter is serial or parallel about queue. If queue is serial then all processes in block run one at a time.
otherwise run all at same time in a queue.
If you create queue privatelly then you need to release it for free up memory space.
dispatch_release(name of private queue).
But in main queue you do not worried about free up it will automatically close when application is close or view is loaded.
For submit any process to queue(any main or private) the method dispatch_async() is called.
dispatch_async(nameof queue,^{//block to executed});
3.)Global Queue: Global queue are also work throughout all project running parallely.
Dispatch_get_global_queue(); method is provided.
Dispatch_get_global_queue(Dispatch_queue_priority_background);
There are some types of global queue in Objective c used accordingly most probably background queue is used.
it works only at priority level.
View is loaded in Main thread only so some time need to work with main thread after loading other thread to call main thread.
you can nested the dispatching of pocess in private queue block.
dispatch_aync(privatequeue.^{
//any background process.
dispatch_get_main_queue(),^{
//Loading view call is here.
}
})
Ok lets we come through GCD approach.
Do you know that who manages all thread like activity in above thread management.
It is the API at low level of like C programming language. GCD is that one who manages all concurrency control activity in objective c. We go through GCD in depth in my next tutorial.
Now look through example.
In my below example if you already familiar with IOS application development then you can easily remember it but if you have not then it is difficult for you to learn MVC.But Do not be upset We will Start programming in IOS very soon.
In ViewController.h
@property (weak, nonatomic) IBOutlet UILabel *StudentName;
- (IBAction)PrintNameWithMain:(id)sender;
- (IBAction)PrintNameWithBackground:(id)sender;
- (IBAction)Update:(id)sender;
In ViewController.m
- (IBAction)PrintNameWithMain:(id)sender{
for(int i=0;i<10000;i++)
{
NSLog(@"The name of Student is printed as %d times",i);
}
self.StudentName.text=@"abc";
}
- (IBAction)PrintNameWithBackground:(id)sender {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
for(int i=0;i<10000;i++)
{
NSLog(@"The name of Student is printed as %d times",i);
}
dispatch_async(dispatch_get_main_queue(), ^{
self.StudentName.text=@"abc";});
});
}
- (IBAction)Update:(id)sender {
self.StudentName.text=@"suraj";
}
In Storyboard
As you run the application you have seen that when you click on main thread then check on Xcode console you find that loop is executed and if you click on update button on that time it will not work and what happen if you delay for 10 second in each time execution of loop. it show like below.
Now click on background thread you have seen in Xcode loop is executed at background but you can also run update button and when loop is executed it run the application.
Source code available here:Download here
I hope you like my tutorial .If you find any query you can comment here and mail me.
My next tutorial about download image from internet in other thread.


This blog is nice and more informative.....
ReplyDeleteMobile App Development Company
Android app Development Company
ios app development Company
Mobile App Development Companies
I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in IOS development, kindly contact us http://www.maxmunus.com/contact
ReplyDeleteMaxMunus Offer World Class Virtual Instructor led training on IOS development . We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
For Demo Contact us:
Name : Arunkumar U
Email : arun@maxmunus.com
Skype id: training_maxmunus
Contact No.-+91-9738507310
Company Website –http://www.maxmunus.com
ReplyDeleteiOS App Development Company USA