Reputation: 161
I have got a problem in my application. My application I have tried to read some data from socket asynchronously and process it synchronously.
Here is the situation
I have running thread (say Thread A ) for accepting data from socket. I have to process this data in another thread , because I don't wanna block this Thread A.
@implementation SocketListener
//Running on Thread A
//Socket data receiving delegate
- (BOOL)onMessage:(NSString *)aMessage response:(NSMutableString *)aResponse {
//Newly created thread
[NSThread detachNewThreadSelector:@selector(addMessage:)
toTarget:[DataProcessor sharedInstance]
withObject:aMessage];
}
@end
@implementation DataProcessor
//Newly created thread say Thread X
- (void) addMessage:(NSString *)aMessage {
//Add message to queue
[[DataStore sharedInstance] pushData:aMessage];
//Want to call in another single thread (Don't wanna run on Thread X)
//Start DataExecutor
[[DataExecutor sharedInstance] startExecution];
}
@end
@implementation DataExecutor
//startExecution
- (void) startExecution {
id data = [[DataStore sharedInstance] popData];
//processing data
//save it to database and send it to server via HTTP
}
@end
@implementation DataStore
//pushData
- (void) pushData:(id)data {
//synchronized
//pushing data to store
}
//popData
- (id) popData {
//synchronized
//poping data and return
}
@end
Here in SocketListener
class I will get the data asynchronously
and I pass it to DataProcessor
to process it. DataProcessor class will save the data to DataStore
to process it later if the DataExecutor
class is busy with processing another data. But my problem is I want to create a single thread in DataExecutor
for the processing. So the startExecution will executed in a single thread and adding data will be run on newly created thread. Can anybody tell me some suggestions on this. If you need more explanation please let me know. Thanks in advance.
Regards, userX
Upvotes: 1
Views: 168
Reputation: 73966
This is the kind of thing NSOperationQueue
is designed for. Use that.
Upvotes: 1
Reputation: 9346
If the effect you want to achieve is that the executor is processing data sequentially, you could start a timer in the DataExecutor class that periodically checks a queue for data to process, and always add data to the queue from your SocketListener class.
Upvotes: 0