iOS线程关键资源加锁

本文详细介绍了如何在Objective-C中利用线程和条件变量实现并发操作,通过实例展示了如何创建和管理两个并发线程,并在特定条件下进行同步。此教程适合希望深入了解Objective-C并发编程的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个view-based application,

viewcontroller.h的代码如下:

#import <UIKit/UIKit.h>

@interface tConditionViewController : UIViewController {
int tickets;
NSThread *t1;
NSThread *t2;
NSCondition *tc;
}
-(void)doSomething:(id)tname;
@end

viewcontroller.m的代码如下:

#import "tConditionViewController.h"

@implementation tConditionViewController
-(void)doSomething:(id)tname
{
NSString *name = (NSString *)tname;
while (TRUE) {
NSLog(@"in thread %@", name);
[NSThread sleepForTimeInterval:1];
[tc lock];
NSLog(@"kkkk");
[tc unlock];
}
}
- (void)dealloc
{
[super dealloc];
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
tc = [[NSCondition alloc] init];
t1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"1"];
[t1 start];
t2 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"2"];
[t2 start];
[super viewDidLoad];
}


- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值