3

我正在创建和加载很多纹理(由字符串组成)。为了保持动画流畅运行,我将工作卸载到一个单独的工作线程。它似乎或多或少完全按照我想要的方式工作,但在旧设备(iPhone 3GS)上,我有时会注意到很长(1 秒)的延迟。它只是有时会发生。现在我想知道我是否正确执行此操作,或者是否存在任何概念问题。我将源代码粘贴在下面。

我还应该提到我不想使用 GLKit TextureLoader,因为我还想将纹理生成工作卸载到另一个线程,而不仅仅是加载部分。

如果您想知道我需要这些纹理做什么,请观看此视频:http: //youtu.be/U03p4ZhLjvY ?hd=1

NSLock*                     _textureLock;
NSMutableDictionary*        _texturesWithString;
NSMutableArray*             _texturesWithStringLoading;

// This is called when I request a new texture from the drawing routine. 
// If this function returns 0, it means the texture is not ready and Im not displaying it.

-(unsigned int)getTextureWithString:(NSString*)string {
    Texture2D* _texture = [_texturesWithString objectForKey:string];
    if (_texture==nil){
        if (![_texturesWithStringLoading containsObject:string]){
            [_texturesWithStringLoading addObject:string];
            NSDictionary* dic = [[NSDictionary alloc] initWithObjectsAndKeys:string,@"string", nil];
            NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadTextureWithDictionary:)object:dic];
            thread.threadPriority = 0.01;
            [thread start];
            [thread release];
        }
        return 0;
    }
    return _texture.name;
}

// This is executed on a separate worker thread.
// The lock makes sure that there are not hundreds of separate threads all creating a texture at the same time and therefore slowing everything down. 
// There must be a smarter way of doing that. Please let me know if you know how! ;-)
-(void)loadTextureWithOptions:(NSDictionary*)_dic{
    [_textureLock lock];
    EAGLContext* context = [[SharegroupManager defaultSharegroup] getNewContext];
    [EAGLContext setCurrentContext: context];

    NSString* string = [_dic objectForKey:@"string"];
    Texture2D* _texture = [[Texture2D alloc] initWithStringModified:string];

    if (_texture!=nil) {
        NSDictionary* _newdic = [[NSDictionary alloc] initWithObjectsAndKeys:_texture,@"texture",string,@"string", nil];
        [self performSelectorOnMainThread:@selector(doneLoadingTexture:) withObject:_newdic waitUntilDone:NO];
        [_newdic release];
        [_texture release];
    }
    [EAGLContext setCurrentContext: nil];
    [context release];
    [_textureLock unlock];
}

// This callback is executed on the main thread and marks adds the texture to the texture cache. 
-(void)doneLoadingTextureWithDictionary:(NSDictionary*)_dic{
    [_texturesWithString setValue:[_dic objectForKey:@"texture"] forKey:[_dic objectForKey:@"string"]];
    [_texturesWithStringLoading removeObject:[_dic objectForKey:@"string"]];
}
4

1 回答 1

0

The problem was that too many threads were started at the same time. Now I am using a NSOperationQueue rather than NSThreads. That allows me to set maxConcurrentOperationCount and only run one extra background thread that does the texture loading.

于 2012-07-14T01:17:51.090 回答