2

I am writing an application that is going to send/receive data over tcp connections and I wanted to schedule the read/write to happen in the run loop of a different thread. Meaning Thread 1 is creating the connection and scheduling it on the run loop of Thread 2. I am unable to find any way of accessing the run loop of a different thread so I wrote a piece of code that the secondary thread will run which will store its run loop in a globally accessible location. I wanted to know if this is the right way to do it or if there is any other/better way to do the same and also if the way I have done it will cause problems like access to the run loop not being thread safe and causing issues if i attempt to schedule multiple things on the run loop of the same thread from multiple threads.

Something like the following.

[NSRunLoop currentRunLoop] --> This I can do from the thread whose runloop I want to access

NSRunLoop * secondthreadrunloop = [secondthread getRunLoop]; -->But is there anything like this?

Shehzan
  • 287
  • 4
  • 12
  • if you need to build an application making use of TCP, I'd greatly recommmend using this library https://github.com/robbiehanson/CocoaAsyncSocket instead of writing everything by yourself. will save a lot of work and nerves... – nburk Oct 27 '14 at 10:36
  • I am not allowed to use anything other than what apple provides. Thanks though. – Shehzan Oct 27 '14 at 10:43
  • Take a look at "Grand Central Dispatch" (GCD) and the functions dispatch_sync, dispatch_async and dispatch_once – TheDarkKnight Oct 27 '14 at 13:14
  • I know about GCD but I actually want to schedule it on another thread that I have created programmatically. I do not want to use any async library or any thing like that. I just want to know if there is any way to access the Run Loop of another thread and also if it is thread safe. – Shehzan Oct 28 '14 at 08:52

1 Answers1

0

I encountered the same problem recently and it seems that the answer is - no, you cannot schedule anything on a NSRunLoop running on a different thread. Apple says that NSRunLoop is not thread safe which means that attaching an NSTimer instance to it would result in an undefined behaviour (I have checked it, in my case it randomly generates crashes).

What can be done though is to schedule a repeating timer from the background thread itself and make it pick up the work you want it to do from some atomic property.

Terminus
  • 925
  • 10
  • 23