[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
How to terminate another thread?
From: |
Stefan Urbanek |
Subject: |
How to terminate another thread? |
Date: |
Tue, 23 Jul 2002 15:35:47 +0200 |
Hello,
I need a proxy of an object in another thread for handling asynchronous
messages. One object may handle messages in more than one thread. I do it like
described later. When the proxy is no more needed I would like to terminate
the thread. Is there a way how it is possible to control another thread?
--- CODE BEGIN ---
static NSMutableDictionary *requestDict = nil;
static int requestID = 0;
@implementation NSObject(AsynchronousProxy)
- (NSDistantObject *)proxyInNewThread
{
NSMutableArray *array = [NSMutableArray array];
NSConnection *connection;
NSDictionary *dict;
NSPort *port1;
NSPort *port2;
NSLock *lock;
NSDistantObject *proxy;
NSNumber *request;
NSLog(@"Creating new thread proxy for '%@'", self);
if(!requestDict)
{
requestDict = [[NSMutableDictionary alloc] init];
}
port1 = [NSPort port];
port2 = [NSPort port];
connection = [[NSConnection alloc] initWithReceivePort:port1
sendPort:port2];
[connection setRootObject:self];
request = [NSNumber numberWithInt:requestID];
requestID ++;
/* Ports switched here. */
dict = [NSDictionary dictionaryWithObjectsAndKeys:
port2, @"ReceivePort",
port1, @"SendPort",
request, @"ID",
nil, nil];
[NSThread
detachNewThreadSelector:@selector(_establishThreadConnectionUsingParameters:)
toTarget:self
withObject:dict];
NSLog(@"Waiting for connection '%@' in new thread", request);
while(!(proxy = [requestDict objectForKey:request]))
{
[[NSRunLoop currentRunLoop] runUntilDate:
[NSDate dateWithTimeIntervalSinceNow: 1]];
NSLog(@"Still waiting '%@'", requestDict);
}
NSLog(@"Connection established to %@", proxy);
RETAIN(proxy);
[requestDict removeObjectForKey:request];
return AUTORELEASE(proxy);
}
- (void)_establishThreadConnectionUsingParameters:(NSDictionary *)dict
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSConnection *connection;
id proxy;
NSLog(@"Establishing connection to %@", self);
connection = [NSConnection
connectionWithReceivePort:[dict
objectForKey:@"ReceivePort"]
sendPort:[dict
objectForKey:@"SendPort"]];
proxy = [connection rootProxy];
[proxy _concludeNewThreadConnectionTo:self
requestID:[dict objectForKey:@"ID"]];
NSLog(@"Connection established");
[[NSRunLoop currentRunLoop] run];
NSLog(@"Established connection died");
RELEASE(pool);
return;
}
- _concludeNewThreadConnectionTo:(id)anObject
requestID:(NSString *)request
{
NSLog(@"Conclude connection '%@' 0x%p", request, anObject);
[requestDict setObject:anObject forKey:request];
}
@end
-- CODE END ---
Tahnk you very much for any help.
Stefan
- How to terminate another thread?,
Stefan Urbanek <=