对不起这个问题的模糊标题,我想不出一个简洁的句子来解释我遇到的问题。
基本上我想启动多个线程并传递一个具有线程特定值的对象,我可以在该上下文中使用这些值。这是执行此操作的代码
while (count < no_threads) {
_thread_bytes = _file_length / no_threads;
_thread_offset = count * _thread_bytes;
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:_thread_offset],@"thread_offset",
[NSNumber numberWithInt:_thread_bytes], @"thread_bytes",
[NSNumber numberWithInt:count], @"count", nil];
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(processServerThread:) object:args];
[thread start];
count++;
}
每个线程都使用正确的thread_bytes
and调用选择器方法,thread_offset
并且还可以访问GCDAsyncSocket
套接字,因此导致许多使用thread_bytes
and的委托方法调用thread_offset
。这是选择器方法。
- (void)processServerThread:(id)sender
{
NSError *err;
dispatch_queue_t iQueue = dispatch_queue_create("main_server_queue", NULL);
GCDAsyncSocket *socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:iQueue];
if (![socket connectToHost:@"example.com" onPort:8080 error:&err]) {
NSLog(@"Error: couldn't connect to file server....");
return;
}
NSData *message =[[self requestMessageWithOffset:[NSNumber numberWithInt:_thread_offset]
andBytes:[NSNumber numberWithInt:_thread_bytes]]
dataUsingEncoding:NSUTF8StringEncoding];
[socket writeData:message withTimeout:SOCKET_TIMEOUT tag:TAG_FILE_REQUEST_WRITE];
}
如果有 N 个线程正在处理,当我发送请求消息时_thread_offset
,例如如果偏移量是 0、2、4、8该上下文中的唯一偏移量。
另外,线程完成时是否有任何回调方法?