How do I create multiple threads in same class? - iphone

all! I want to create multiple threads in my application. I' using following code for creating a thread.
This' buttonPress method where I'm creating a thread:
- (void) threadButtonPressed:(UIButton *)sender {
threadStartButton.hidden = YES;
threadValueLabel.text = #"0";
threadProgressView.progress = 0.0;
[NSThread detachNewThreadSelector:#selector(startMethod) toTarget:self withObject:nil];
}
This' where I'm calling the method for the thread:
- (void)startMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(threadMethod) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)threadMethod {
float actual = [threadProgressView progress];
threadValueLabel.text = [NSString stringWithFormat:#"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else
threadStartButton.hidden = NO;
}
This thread works properly.
But when I try to create another thread in the same class using the same method, it gets created properly, but at the method "performSelectorOnMainThread", it doesn't execute that method. Can anybody please help me?

It seems that you are trying to queue up methods to be executed on the main thread. You might want to look into an NSOperationQueue and NSOperation objects. If you want to proceed on this path, you might consider changing the repeats parameter to YES. The problem seems to be that the main thread is busy when it's being passed this message. This will cause the main thread to block. You may also consider not using a second threadMethod and calling back to the main thread, but instead wrapping the contents of threadMethod in an #synchronized(self) block. This way, you get the benefits of multi-threading (multiple pieces of code executing at the same time and thus a reactive user interface) without doing some weird stuff with the main thread.

I'm missing the context here. I see a call that creates a new thread, and then I see a call that performs a selector (calls a method) on the main thread..
As I understand, you are calling a function in a new thread (entryMethod), in which you call a method to perform on the main thread (myMethod). I do not understand the point of this, without some background info and possibly some code.
Is it possible that the main thread is busy performing the 'myMethod' function, and thus does not respond to other calls?

Why cant you do it with the same call, by replacing
-(void)startMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(threadMethod) withObject:nil waitUntilDone:NO];
[pool release];
}
with
-(void)startMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
float actual = [threadProgressView progress];
threadValueLabel.text = [NSString stringWithFormat:#"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else
threadStartButton.hidden = NO;
}
[pool release];
}

Related

Thread lock error

I have a timer who run in a runloop, the problem is when the timer end's and the user scroll the page at the same time, the apps crash with the problem:
bool _WebTryThreadLock(bool), 0x18d9be60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
this is the timer:
- (void)startTimer{
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:#selector(startTimerThread) object:nil]; //Create a new thread
[timerThread start]; //start the thread
}
-(void) startTimerThread
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[repeatingTimerEtape invalidate];
NSString * temps;
if (questionCircuit) {
temps = [[Mission singletonMission].circuitTerrain valeurChampEtapeCircuitEnCours:#"et_temps_etape" :FALSE];
}
else {
temps = [[Mission singletonMission].histoireTerrain valeurChampQuestion:#"hi_temps_etape" :FALSE];
}
if (!b_Pause) {
[dateComp setHour:0];
[dateComp setMinute:[[FonctionUtile gauche:temps :2] intValue]];
[dateComp setSecond:[[FonctionUtile droite:temps :2] intValue]];
}
else {
b_Pause = FALSE;
}
self.repeatingTimerEtape = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateLabelTimerEtape:) userInfo:nil repeats:YES];
[runLoop run];
[pool release];
}
thx
Tried to obtain the web lock from a thread other than the main thread or the web thread.
You started a thread then did stuff on it that should only be done on the main thread or the "web thread".
Most likely in your updateLabelTimerEtape: method. Look at the backtrace to know for sure.
Also, valeurChampQuestion::: is a horrible method name. Don't make methods that have arguments that lack a description. valeurChampQuestion:isSelected: would be better (replace isSelected: with a better description -- since others can't tell what it should be from that line of code, that is confirmation that bare arguments are bad).

Keeping track of multiple threads on iphone

I'm trying to do something basic to understand threads with a counter that just increments when a button is pressed, and every time the button is pressed, a new thread incrementing the same counter starts. Then I have a stop button to stop a thread that is running. How can I tell how many threads, or which thread is running? Here is my basic template I am working on. Thanks.
-(int)count {
return count;
}
-(void)setCount:(int) value {
count = value;
}
-(void)updateDisplay {
countLabel = [NSString stringWithFormat:#"%i", count];
count++;
}
-(void)myThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(updateDisplay)
withObject:nil
waitUntilDone:NO];
[pool release];
}
-(void)startThread {
[self performSelectorInBackground:#selector(myThread) withObject:nil];
}
-(void)myThreadStop {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(updateDisplay)
withObject:nil
waitUntilDone:NO];
[pool release];
}
-(void)stopThread {
[self performSelectorInBackground#selector(myThreadStop) withObject:nil];
}
Basically, you want to keep track of the number of threads you have running, and also assign each thread a unique ID. Assuming that startThread is an event handler for your button, you might have something like:
static int threadIndex = 0;
static int threadsRunning = 0;
-(void)startThread {
NSNumber* threadId = [NSNumber numberWithInt:threadIndex++];
threadsRunning++;
[self performSelectorInBackground:#selector(myThread) withObject:threadId];
}
Then when you stop a thread, you just decrement threadsRunning.
Looking at your code, though, I'm confused by your stopTread method, since it seems to be doing the exact same thing as the myThread method, i.e., not stopping the thread at all.
You're performing stuff in the background, which is distinct from explicitly creating threads (e.g. it might reuse threads in a thread pool).
If you want really inefficient threading code, you could use something like this:
NSThread * thread = [[[NSThread alloc] initWithTarget:self selector:#selector(myThread) object:nil] autorelease];
[thread start];
while ([thread isExecuting])
{
NSLog(#"Still running");
[NSThread sleepForTimeInterval:0.1];
}
EDIT: If you're actually going to do iPhone development, I recommend looking at NSOperation/NSInvocationOperation/NSBlockOperation instead. Thread management is a real pain to get right.

view hierarchy refresh timing

I'm trying to add a progress meter, or other "I'm busy right now" notification to my view hierarchy right before doing some intense computation that will block the UI. My code looks some thing like:
//create view
[currentTopView addSubView:imBusyView];
//some initialization for the intense computation
[computation startComputing];
Unfortunately, my progress meter doesn't display until after the computation completes. It appears like the views aren't re-drawn until the run loop completes. I'm pretty sure that setNeedsDisplay and setNeedsLayout will also wait until the run loop completes.
How do I get the view to display immediately?
Redrawing only occurs when your code returns control to the run loop. So the easiest way would be for you to schedule the startComputing call with a zero delay. That way, it will be executed during the next run loop iteration (right after redrawing):
[computation performSelector:#selector(startComputing) withObject:nil afterDelay:0.0];
Be aware, though, that unless you do your computation in another thread you will not be able to update the UI during the computation.
If you are doing heavy calculations maybe spawning a new thread is a good idea.
Here I have an activityIndicator displayed and starts a large XMLParse operation in a background thread:
- (void) setSearchParser {
activityIndicator = [[ActivityIndicatorView alloc] initWithActivity];
[self.view addSubview:activityIndicator];
[NSThread detachNewThreadSelector:#selector(getSearchResults:) toTarget:self withObject:[searchParser retain]];
}
then the getSearchResults method:
- (void) getSearchResults: (SearchResultParser *) parser {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[parser startParser];
[self performSelectorOnMainThread:#selector(searchResultsReady:) withObject:[parser data] waitUntilDone:NO];
[pool release];
}
So firstly make a new thread:
[NSThread detachNewThreadSelector:#selector(getSearchResults:) toTarget:self withObject:[searchParser retain]];
this means that all code inside the getSearchResults will be executed on a different thread. getSearchResults also get's passed a parameter of "searchParser" thats a large object that just needs startParse called on it to begin.
This is done in getSearchResults. When the [parser startParser] is done, the results is passed back to the main thread method called "searchResultsReady" and the threads autorelease pool is released.
All the time it took from my parser began to it had finished, a gray view covered the screen an an activityIndicator ran.
You can have the small activityIndicator class I wrote:
-(id) initWithActivity {
[self initWithFrame:[self bounds]];
[self setBackgroundColor:[UIColor blackColor]];
[self setAlpha:0.8];
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.center = CGPointMake(160, 240);
[self addSubview:activityView ];
[activityView startAnimating];
return self;
}
- (void) dealloc {
[activityView release];
[super dealloc];
}
Hope it helps you out, even though threads seems a bit confusing, they can help to make the UI not freeze up, which is especially important on the iPhone.

Is calling -setNeedsDisplay from a background task asking for trouble?

I have a background task that updates a view. That task calls -setNeedsDisplay to have the view drawn.
This works:
- (void) drawChangesTask;
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (pixels) {
drawChanges((UInt32 *) origPixels, (UInt32 *) pixels, CGBitmapContextGetBytesPerRow(ctx)/4, CGBitmapContextGetHeight(ctx), count--);
if (count < 0) {
count = 150;
}
else
[self performSelectorInBackground:#selector(drawChangesTask) withObject:nil ];
[self performSelectorOnMainThread:#selector(setNeedsDisplay) withObject:nil waitUntilDone:NO ];
}
[pool release];
}
This does not work:
- (void) drawChangesTask;
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (pixels) {
drawChanges((UInt32 *) origPixels, (UInt32 *) pixels, CGBitmapContextGetBytesPerRow(ctx)/4, CGBitmapContextGetHeight(ctx), count--);
if (count < 0) {
count = 150;
}
else
[self performSelectorInBackground:#selector(drawChangesTask) withObject:nil ];
[self setNeedsDisplay];
}
[pool release];
}
Anyone know why? When I say it doesn't work, I mean that it runs tens of iterations, sometimes I see portions of my image shifted up or down, or entirely blank, and then the deugger give me an “EXC_BAD_ACCESS” somewhere in CoreGraphics.
Also, if I don't handle the autorelease pool myself, then I get leaking error messages. Don't understand why that is either. My drawChanges() doesn't create any new objects. Here's the error:
2009-08-17 11:41:42.358 BlurApp[23974:1b30f] *** _NSAutoreleaseNoPool(): Object 0xd78270 of class NSThread autoreleased with no pool in place - just leaking
UIKit simply isn't thread-safe — you need to call methods that update UIKit controls on the main thread.
I think that this line:
[self performSelectorInBackground:#selector(drawChangesTask) withObject:nil];
Is causing trouble. Have you tried simply calling it again on the current thread? If you need the runloop to execute between the calls, use:
[self performSelector:#selector(drawChangesTask) withObject:nil afterDelay:0.0];
This will call the method on the current thread after the method you're in has finished and the runloop has gone round once.
Problem here is that UIKit is not thread safe, if you tell your UI to do something from a background thread nothign is guaranteed, what you want to do is use the performSelectorOnMainThread method to do updates t o your UI elements

when is it safe to release an NSThread?

Below is the runloop for my secondary NSThread* processThread
To close the thread I call
//cancel secondary thread
[processThread cancel]
//signal condition
[processCondition broadcast];
Is it then safe to then call:
[processCondition release];
[processThread release];
or do i need to be sure that the thread has finished?
Perhaps like this?
NSTimeInterval timeout = [NSDate timeIntervalSinceReferenceDate] + (1.0/15.0);
while ([processThread isExecuting] && [NSDate timeIntervalSinceReferenceDate] < timeout)
{
[NSThread sleepForTimeInterval: 1.0/1000.0 ];
}
[processCondition release];
[processThread release];
detailed code and explanation:
- (void)processLoop
{
NSAutoreleasePool * outerPool = [[NSAutoreleasePool alloc] init];
[processCondition lock];
//outer loop
//this loop runs until my application exits
while (![[NSThread currentThread] isCancelled])
{
NSAutoreleasePool *middlePool = [[NSAutoreleasePool alloc];
if(processGo)
{
//inner loop
//this loop runs typically for a few seconds
while (processGo && ![[NSThread currentThread] isCancelled])
{
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc]; init];
//within inner loop
//this takes a fraction of a second
[self doSomething];
[innerPool release];
}
[self tidyThingsUp];
}
else
{
[processCondition wait];
}
[middlePool release];
}
[processCondition unlock];
[outerPool release];
}
the combination of:
an inner while loop
NSCondition *processCondition
toggling processGo between YES and NO
allows me to stop and start the inner while loop without cancelling the thread.
if (processGo == YES)
execution enters the inner while loop.
When the main thread sets
processGo = NO
execution leaves the inner while loop and tidys up
on the next pass of the outer loop, execution hits
[processCondition wait]
and waits
if the the main thread resets
processGo == YES
and calls
[processCondition wait]
execution re-enters the inner loop
Yes, it is safe to call release against an NSThread if you are done with it. In non-GC Objective C code the idiom is that once you are done accessing an object you may release it. If anything else needs that object, including the object itself it their job to have a retain against it. In general if an object cannot be safely disposed at arbitrary times it will retain itself while it is in an unsafe state, and release itself when it can be safely disposed of.
This is how things like NSThread and NSURLConnection work (NSURLConnection actually retains its delegate and does a lot of fancy stuff to cope with the retain loop that occurs.