Early experience in multi-thread programming for iPhone Posted on June 8, 2010 By Aminby
It took one day to complete the multi-thread programming for the iPhone. The class used was nsthread in uikit.
PS: During the Google process, I found many articles with the title similar to <multi-threaded os4 coming>. These ideas are a positive guide. The highlight of 0s4 is multi-task. A task is a process, it is also called multi-process, and multithreading was available on early iPhone OS.
In iPhone OS, the concept of a task is an application. You can only do one thing at a time, that is, you cannot play games at the same time, while playing QQ at the same time.
The process is as follows:
1. Create a thread
- [Nsthread detachnewthreadselect: @ selector (beginthread)
- Totarget: selft
- Withobject: Nil];
2. Do two jobs in the thread. One is dosomethinglongtime in the background processing, and the other is updateui)
View plaincopy to clipboardprint?
- -(Void) Beginthread {
- [Self defined mselectorinbackgroud: @ selector (dosomethinglongtime)
- Withobject: Nil];
- [Self perfomselecw.mainthread: @ selector (updateui)
- Withobject: Nil
- Watuntildone: No];
- }
3. How does updateui data come from?
View plaincopy to clipboardprint?
- -(Void) Dosomethinglongtime {
- // Modify the shared variables varprogress, vartext, and so on.
- }
- -(Void) Updateui {
- // Obtain the shared variables varprogress and vartext, which are displayed on the interface.
- }
This completes a general process, but the while (1) cannot be used in updateui. Otherwise, the main thread will be blocked in the updateui function. What should I do? Google has a method, and the updateui method has been modified.
View plaincopy to clipboardprint?
- -(Void) Updateui {
- // Obtain the shared variables varprogress and vartext, which are displayed on the interface.
- If(! Finished)
- [Nstimer scheduledtimerwithtimeinterval: 0.2
- Target: Self
- Selector: @ selector (updateui)
- Userinfo: Nil repeats: No];
- }
This means that if no thread is finished, the function will return to the function update interface after 0.2 seconds, so the loop ends until the end.
One of the above methods of multi-thread programming for the iPhone, of course, some people suggest using nsoperation and nsoperationqueue, but I tried it and didn't try it out. I will try it again when there is a result.