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.
There are 2 serious errors in your code:
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.
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.