Sen*_*esh 4 macos multithreading objective-c nsthread objective-c-blocks
我正在编写一个同时执行多项任务的应用程序.一个特殊的任务是每200毫秒做一次工作.为实现这一点,我使用了两种相互调用的方法.第一种方法只调用第二种方法,第二种方法使用dispatch_after()以延迟调用第一种方法.
经过几次迭代(300-400次)后,dispatch_after中的块在200 ms后不会执行.执行块需要大约5-10秒.请让我知道行为的原因(延迟).我也试过NSThread(sleepForTimeInterval :),我也遇到了同样的问题.我卡住了.请帮我.
代码如下.
Screen.h
#import <Foundation/Foundation.h>
@interface Screen : NSObject
-(void) firstMethod;
-(void) secondMethod;
@end
Run Code Online (Sandbox Code Playgroud)
Screen.m
#import "Screen.h"
@implementation Screen
int i=0;
dispatch_queue_t another_queue;
dispatch_time_t pop_time;
-(Screen*) init {
self = [super init];
if (self) {
another_queue = dispatch_queue_create("com.test.timer.2", NULL);
}
return self;
}
-(void) firstMethod {
i++;
NSLog(@"i value : %d",i);
[self secondMethod];
}
-(void) secondMethod {
pop_time = dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC);
dispatch_after(pop_time, another_queue, ^(void){
[self firstMethod];
});
}
@end
Run Code Online (Sandbox Code Playgroud)
AppDelegate.h
#import <Cocoa/Cocoa.h>
#import "Screen.h"
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@end
Run Code Online (Sandbox Code Playgroud)
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
Screen* screen = [[Screen alloc] init];
dispatch_queue_t first_queue = dispatch_queue_create("com.test.timer", NULL);
dispatch_block_t blk =^(void) {
[screen firstMethod];
};
dispatch_async(first_queue, blk);
}
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1107 次 |
| 最近记录: |