iPhoneでマルチスレッドプログラミングとスレッドロックをどのように行うか.

13413 ワード

http://disanji.net/2011/04/23/iphone-how-multi-thread/
マルチスレッドは様々なプログラミング言語で難点であり、多くの言語で実現するのは面倒であり、objective-cはcに由来するが、そのマルチスレッドプログラミングはかなり簡単でjavaに匹敵する.この文章は主にスレッドの作成と起動、スレッドの同期とロック、スレッドのインタラクション、スレッドプールなどの4つの面からiphoneのマルチスレッドプログラミングを簡単に説明します.
一、スレッド作成と起動スレッド作成には主に二つの方法がある.
1
2
- (id)init;	// designated initializer
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

もちろん、いわゆるconvenient methodを使用すると、スレッドを直接生成して起動することができ、スレッドのクリーンアップに責任を負う必要はありません.このメソッドのインタフェースは、次のとおりです.
1
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

最初の2つの方法が作成された後、携帯電話を起動する必要があります.起動する方法は次のとおりです.
- (void)start;
二、スレッドの同期とロックはスレッドの同期とロックを説明し、最良の例は複数の窓口で同時に切符を販売する切符販売システムである可能性がある.Javaではsynchronizedを使用して同期することが知られていますが、iphoneではjavaの下のsynchronizedのようなキーワードは提供されていませんが、NSConditionオブジェクトインタフェースが提供されています.NSConditionのインタフェースの説明を見ると、NSConditionはiphoneの下のロックオブジェクトであるため、NSConditionを使用してiphoneのスレッドセキュリティを実現することができます.これはネット上の例です.SellTicketsAppDelegate.hファイルです.
1
2
3
4
5
6
7
8
9
10
11
12
13
//  SellTicketsAppDelegate.h
import <UIKit/UIKit.h>
 
@interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {
     int tickets;
     int count;
     NSThread* ticketsThreadone;
     NSThread* ticketsThreadtwo;
     NSCondition* ticketsCondition;
     UIWindow *window;
 }
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end

SellTicketsAppDelegate.mファイル
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//  SellTicketsAppDelegate.m
import "SellTicketsAppDelegate.h"
 
@implementation SellTicketsAppDelegate
@synthesize window;
 
- (void)applicationDidFinishLaunching:(UIApplication *)application {
     tickets = 100;
     count = 0;
     //    
     ticketCondition = [[NSCondition alloc] init];
     ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
     [ticketsThreadone setName:@"Thread-1"];
     [ticketsThreadone start];  
 
 
     ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
     [ticketsThreadtwo setName:@"Thread-2"];
     [ticketsThreadtwo start];
     //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
      // Override point for customization after application launch
     [window makeKeyAndVisible]; 
 
 }
 
- (void)run{
     while (TRUE) {
     	//   
         [ticketsCondition lock];
         if(tickets > 0){
             [NSThread sleepForTimeInterval:0.5];
             count = 100 - tickets;
             NSLog(@"     :%d,  :%d,   :%@",tickets,count,[[NSThread currentThread] name]);
             tickets--;
         }else{
             break;
         }
         [ticketsCondition unlock];
     }
 }
 
- (void)dealloc {
	[ticketsThreadone release];
     [ticketsThreadtwo release];
     [ticketsCondition release]; 
     [window release];
     [super dealloc];
}
@end

三、スレッドのインタラクティブスレッドは実行中に、メインスレッドでインタフェースを変更するなど、他のスレッドと通信する必要がある場合があります.以下のインタフェースを使用できます.
1
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

このプロセスでは、いくつかのリソースを解放する必要がある場合があります.次のように、NSAutoreleasePoolを使用して管理する必要があります.
1
2
3
4
5
6
7
- (void)startTheBackgroundJob {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // to do something in your thread job
    ...
    [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
    [pool release];
}

何も考えずにスレッド関数内でautoreleaseを呼び出すと、NSAutoReleaseNoPool():Object 0 x*****of class NSConreteData autoreleased with no pool in place....というエラーが発生します.
四、スレッドプールについては、NSOperationに関する資料を見ることができます.テキストリンク:http://www.voland.com.cn/iphone-in-the-multi-threaded-programming