Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a piece of code run in a separate thread?

I have a few method calls like this:

[self myFoo];
[self heavyStuff]; // this one in other thread
[self myBar];

which classes / methods do I have to look at? When I search for "thread", there comes a lot of classes, methods and functions. Which one's are most apropriate here?

like image 245
Thanks Avatar asked May 28 '09 22:05

Thanks


People also ask

Can I run a method in a separate thread?

Here is the main method which can run a method in a separate thread: This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

How to make code only run once in a method?

If you want to make code only run once, you could have code in the method overwrite the method with NOP's after the method is complete. This way if the method were to run again, nothing would happen. This will break a few architectures that write protect program memory or run from ROM.

How do I run code from a runnable?

Put the code you want to run in the run() method - that's the method that you must write to comply to the Runnable interface. In your "main" thread, create a new Thread class, passing the constructor an instance of your Runnable, then call start() on it.

How do I run a runnable in a thread?

In your "main" thread, create a new Thread class, passing the constructor an instance of your Runnable, then call start () on it. start tells the JVM to do the magic to create a new thread, and then call your run method in that new thread. Take a look at Java's concurrency tutorial to get started.


1 Answers

You would do

[self performSelectorInBackground:@selector(heavyStuff) withObject:nil];

See the NSObject reference on Apple's site.

like image 170
Marc W Avatar answered Oct 11 '22 12:10

Marc W