-1

I have created two thread using and

static int counter (global variable) ;
-(void)ViewDidLoad {
    [NSThread detachNewThreadSelector:@selector(handleTread:) toTarget:self withObject:nil];
    [NSThread detachNewThreadSelector:@selector(handleTread:) toTarget:self withObject:nil];
}

and selector method is

-(void)handleTread:(NSThread*)sender {
    counter =0; // Position-1
    while (counter<9) {
        counter =0; // Position-2
        counter++;
    }
    NSLog(@"Counter=%d",counter);
}

So if I use counter at Position-1 it prints the result as counter=9. But I placed it at Position-2 it does not print? I have updated the question.

Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75
  • What do you mean by "use counter"? Do you mean examine its value in `lldb`? Also you do realize that loop will never terminate? – trojanfoe Jul 24 '15 at 10:14
  • your code not complete while loop,always you setting counter =0; in while loop, your maximum value of counter is 1, – NANNAV Jul 24 '15 at 10:17
  • @NANNAv, counter is static so it wont initialised with zero after first time even I placed it position 1. right? – Sanoj Kashyap Jul 24 '15 at 10:26
  • @trojanfoe, I am confused with static keyword, as if out side while it not re assigned with zero then why it should be with in while loop? static class level object and it will same for all instances. right? Please, explain. – Sanoj Kashyap Jul 24 '15 at 10:31
  • I don't see the `static` keyword anywhere in your code. – trojanfoe Jul 24 '15 at 10:34
  • static int counter (global variable) check this line. – Sanoj Kashyap Jul 24 '15 at 10:35
  • @Sandy Ah yes. As my answer states you have two serious errors that have nothing to do with the `static` keyword; until those are resolved it's hard to see how `static` is important. – trojanfoe Jul 24 '15 at 10:36

2 Answers2

2

There are 2 serious errors in your code:

  1. You have two threads of execution manipulating the same global variable. One thread will trample over the variable used by the other. For example thread #1 might be able to get counter to 1 and then thread #2 will reset it back to 0 again. The exact behaviour is undefined.

  2. You have an infinite loop (you assign counter = 0 within the while statement), even if the code was executed in a single thread it would never complete.

Fundamentally your code is broken and I'm not sure I can say much more about it.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Code works fine if I placed counter and postion -1 or before creating thread. my question is will counter=0 within while loop will re assign value 0 in while loop even though it static? – Sanoj Kashyap Jul 24 '15 at 10:38
  • @Sandy Sorry I don't understand what you're asking me. – trojanfoe Jul 24 '15 at 10:39
0

If you set your counter in the while loop it will lead to an infinite loop and your NSLog will never be reached. Keep your counter at position 1.

ryancrunchi
  • 465
  • 2
  • 16