3

I'm kind of new to multithreading, and need some advice.

I'm using ARC in my code.

Problem : I've set up NSTimer in my app to fire every 1 second some method which creates and starts thread like this

//Create a new thread
mSomeThread = [[NSThread alloc] initWithTarget:self selector:@selector(someMethod) object:nil]; 

//start the thread 
[mSomeThread start]; 

Where mSomeThread is an ivar

Let say the execution of mSomeThread takes more than 1 second, and the mSomeThread is allocated second time, i.e. according to ARC "rules" its released before be allocated one more time.

Does it mean that the first thread doesn't complete and and is forced to quite ?

deimus
  • 9,565
  • 12
  • 63
  • 107
  • This may help: http://stackoverflow.com/questions/7149403/nsthreads-in-automatic-referenc-countingarc – Adam Jun 03 '12 at 08:03
  • Thanks for the link, but your pointing me to totally different issue, I know about the autorelease pools and have added it into my code already. – deimus Jun 03 '12 at 08:09
  • 3
    @deimus: Don't use thread if possible. Use GCD to spawn threads for you: http://www.fieryrobot.com/blog/2010/06/12/threading-is-dead-long-live-threading/ – nhahtdh Jun 03 '12 at 08:15
  • Another link: http://stackoverflow.com/a/1151746/730701 – Adam Jun 03 '12 at 08:26

2 Answers2

0

An NSThread retains itself for the duration of its execution. There's no risk that resetting mSomeThread will cause a running thread to be terminated prematurely.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
-1

Yes. If you really need to keep reference to the current thread of execution for your someMethod then you need to wait for it to complete before you can actually start a new thread. A quick way of doing this would be to add

while ([mSomeThread isExecuting]) {
    sleep(1);
}

immediately after [mSomeThread start];.

By the way I'd rather re-implement NSThread and setup a repetitive NSTimer inside its main implementation. Something like:

- main {
      @autoreleasepool {
          [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(someMethod) userInfo:nil repeats:NO];
          [[NSRunLoop currentRunLoop] run];
        }
}
alediaferia
  • 2,537
  • 19
  • 22
  • Using sleep() as a synchronization primitive is wrong; it'll block the calling thread, use unnecessary resources, and lead to other problems. – bbum Jun 03 '12 at 17:58