Apple のスレッド プログラミング ガイドを読み始めたところです。
私はスレッドを開始し、それへの参照を持っています
self.myThread = [[NSThread alloc] initWithTarget: self
selector: @selector(myThreadMain)
object: nil];
[self.myThread start];
threadMain はドキュメントのサンプルコードのように見えます。
このスレッドを終了するには、コード内の「exitNow」変数をメイン スレッドから変更する必要がありますが、その方法がわかりません。
myThreadMain ループは、作業を実行していないときにスリープする必要がありますが、実装方法もわかりません。
ドキュメントには、新しいスレッドがすぐに終了しない場合、少なくとも 1 つの入力ソースが必要であると書かれていますが、新しいスレッドは「今すぐ終了」メッセージと performSelector:onThread: 呼び出しを受け取るだけで済みます。
入力ソースを設定する必要がありますか?
- (void) myThreadMain
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
BOOL exitNow = NO;
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
// Add the exitNow BOOL to the thread dictionary.
NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
[threadDict setValue:[NSNumber numberWithBool:exitNow] forKey:@"ThreadShouldExitNow"];
// Install an input source.
// [self myInstallCustomInputSource];
while (!exitNow)
{
// Do one chunk of a larger body of work here.
// Run the run loop but timeout immediately if the input source isn't waiting to fire.
[runLoop runUntilDate:[NSDate date]];
// Check to see if an input source handler changed the exitNow value.
exitNow = [[threadDict valueForKey:@"ThreadShouldExitNow"] boolValue];
}
[pool release];
}
私はいくつかの仕事をこのスレッドに渡すつもりです
performSelector:onThread:withObject:
実行するセレクターは次のように定義する必要があります
が、これを実現する方法もわかりません。
- (void) selectorToPerformInThread
{
for( int i = 0; i < 10; ++i )
{
do something;
**if(received a new "selectorToPerformInThread" call
when we are still in this loop)
break out and let the new "selectorToPerformInThread"
in order to run from the beginning of loop**
}
}
それはたくさんの質問です...
私の質問を繰り返しさせてください。
- threadDictに格納されている「exitNow」変数の設定方法。
- 作業が必要ないとき (セレクターを実行していないとき) にスリープするようにスレッドをセットアップする方法。
- スレッドがすぐに死なないように、入力ソースを設定する必要がありますか?
- 「performSelector」への呼び出しごとに、同じセレクター(実行中の場合)がキャンセルされ、最初から実行されるように実行ループを設定する方法は?
前もって感謝します。