NSThread with a delegate? Impossible? A Better way?

adamfenn28's picture

I want to launch a daemon on new thread, to my program doesn't lock up while waiting for input from the daemon, but I need a way for the main program to get information back from the daemon. I've used NSThread to fire off a new thread, but I don't see how to use a delegate with NSThread.

For more context, I'm working on a custom patch for that will receive data from the network. Specifically, multicast with via a externally configurable address and port, without 32 byte characters. The idea is that a second thread could run the daemon, and on each frame, I'd grab the new data from an ivar set by a delegate method when the daemon thread received new data.. all the while, the composition runs along with no interruption.

Can I do this with NSThread? Is there a better way I should be looking at?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

adamfenn28's picture
A better multicast receiver

I've just finished, almost, an improved multicast receiver. I thought I'd share it here in case anyone felt like it might be useful to them, or if anyone wanted to critique my work.

It allows you to specify the multicast address and port number via input ports, and it uses UTF8 encoding instead of the 32 bit format the built in network receiver uses. It's also got a 1024 byte character limit instead of 256. I'll attach the files I used, an the sample tester program I used to test it out.

Critique welcome!

Oh.. almost forgot.. right now, once the daemon starts, it won't restart when you change the input values. You'll have to restart the composition to make the changes take effect. I need to figure out how to cancel the NSThread the daemon runs in while he's blocked listening for a packet.

Archive.zip8.9 KB

dust's picture
Re: NSThread with a delegate? Impossible? A Better way?

There are various ways to send your variables to your thread. Usually a perform selector on the specific thread you want will work. You could also add a target to your variable by assigning your threads method as the target. Seems like you figured this out. In order to stop a thread you it's probably best to make a variable for your thread and then set the threads is canceled property to yes from outside the thread. Then inside the thread you will want to check the is cancelled property for truth and subsequently call thread exit if the thread has been canceled. Then you you can set the thread to nil or release etc... I'm sure there are other ways like subclassing and defining a protocol that encapsulates the delegate you want In. That way whe you instantiste that subclass in your background thread the custom protocol you defined should fire it's delegate method inside your background thread supposing you set the delegate to self.