In Java, the thread safe PipedInputStream
and PipedOutputStream
classes can be used for transferring data from one thread to another thread. What is its equivalent in iOS?
Please correct me if I am wrong, but my understanding is that NSPipe
from Cocoa is only used for the transfer of data between processes but not between threads. In addition, since it makes use of some local directory for this, I would assume that some temporary file is used for such transfers. To summarize,
Unlike POSIX threads created with fork, Java threads are lightweight and share the same address space. There is no need for C-Style IPC in Java, and PipedInputStream/PipedOutputStream were definitely not created for that purpose. Objective-C threads are built on POSIX, but they all share the same virtual memory space, so you typically will not do any IPC in ObjC either.
If your looking to 'share' data between threads in Objective C, just write it to an appropriate variable, and if necessary, send a signal between the threads that the data is available to be used. The best way to do this is via the use of Conditions.
If you are going to do any non-trivial threading work in Obj C then I highly recommend you read Apple's guide on thread safety.
The easiest way to transfer data between threads is to use NSData objects along with performSelector:onThread:withObject.
performSelector:onThread:withObject:waitUntilDone:modes
Assume you have two threads, threadX and threadY, each with one object, objectX and objectY. Do something like:
char buffer[100] = "Hello";
NSData *data = [NSData dataWithBytes:byBuffer length:100];
[objectY performSelector:@selector(haveSomeData:) onThread:threadY withObject:data waitUntilDone:NO modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With