Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transfer data between threads in iOS?

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,

  1. Assuming that Operation Queues are used, what class can I use in Cocoa to transfer binary data from one thread to another without writing my own synchronization and without making use of temporary files?
  2. If there isn't any, what would be an elegant alternative?
like image 269
Lopper Avatar asked Aug 12 '11 01:08

Lopper


2 Answers

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.

like image 77
Perception Avatar answered Sep 27 '22 16:09

Perception


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]];
like image 31
EricS Avatar answered Sep 27 '22 17:09

EricS