pthread
与pthread_mutex_t
在一些场景下,会经常结合使用。
示例
1.头文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// QBKThread.h
@interface QBKThread : NSObject
{
pthread_t _tid;
pthread_mutex_t theTaskMutex;
}
- (void*)run;
- (void)start;
- (void)stop;
@end
|
2.实现文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
// QBKThread.m
#import "QBKThread.h"
#import <pthread.h>
void *backgroundProcessThread(void *p)
{
QBKThread* t = (QBKThread *)p;
return [t run];
}
@interface QBKThread()
{
BOOL _isRunnig;
}
@end
@implementation QBKThread
- (id)init {
self = [super init];
if (self) {
pthread_mutex_init(&theTaskMutex, NULL);
}
return self;
}
- (void)dealloc {
[self stop];
pthread_mutex_destroy(&theTaskMutex);
[super dealloc];
}
-(void*)run {
while (_isRunnig) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
pthread_mutex_lock(&theTaskMutex);
NSLog(@"01");
pthread_mutex_unlock(&theTaskMutex);
[NSThread sleepForTimeInterval:0.16];
[pool release];
}
return 0;
}
- (void)start {
pthread_mutex_lock(&theTaskMutex);
if (!_isRunnig) {
_isRunnig = YES;
pthread_create(&_tid, NULL, backgroundProcessThread, self);
}
pthread_mutex_unlock(&theTaskMutex);
}
- (void)stop {
pthread_mutex_lock(&theTaskMutex);
if (_isRunnig) {
_isRunnig = NO;
//printf("exitThread:(BOOL)bHandleCancel exitNow = YES;\n");
pthread_join(_tid, NULL);
NSLog(@"thread close");
}
pthread_mutex_unlock(&theTaskMutex);
}
|
文章作者
梵梵爸
上次更新
2013-04-03
许可协议
原创文章,如需转载请注明文章作者和出处。谢谢