If the lock is not synchronized, the code is as follows: #import "ViewController.h"
@interface Viewcontroller ()
{
Nsinteger _money;
}
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
_money = 100;
Nsthread *t1 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
Nsthread *t2 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
Nsthread *t3 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
Nsthread *T4 = [[Nsthread alloc]initwithtarget:self selector: @selector (dothing) Object:nil];
T1.name = @ "I am--t1";
T2.name = @ "I am--t2";
T3.name = @ "I am--t3";
T4.name = @ "I am--t4";
[T1 start];
[T2 start];
[T3 start];
[T4 start];
}
-(void) dothing{
for (int. i=0;i<3;i++) {[Self getmoney:10]; } }
-(void) Getmoney: (Nsinteger) money{
Check balance
if (_money >= money) {
[Nsthread Sleepfortimeinterval:2];
_money-= money;
NSLog (@ "%@----Balance:%ld", [Nsthread Currentthread],_money); }}//print results, random: obvious dirty data//improvements: Thread Lock: 1. Create a Lock object Nslock, and instantiate _lockcondition = [[Nslock alloc]init];2. Determine if there is a lock, do not enter and lock. if ([_lockcondition Trylock]) {//In the inside do take money operation//withdraw money after the completion of the unlock [_lockcondition unlock];} After the improvement: a total of 12 times, only 4 times the operation was successful. 0422_ Review _ thread synchronization. zip
25.0 KB
Requirements: If you really want to take the money, it should be as follows:
//locking, unlock after operation is complete.Visible: After locking, both the operator and the operating thread are orderly ...
0422 thread sync/sync lock to prevent dirty data