iOS 开发实用技术导航
NSHipster 中文版
› http://nshipster.cn/
cocos2d 开源 2D 游戏引擎
› http://www.cocos2d-iphone.org/
CocoaPods
› http://cocoapods.org/
Google Analytics for Mobile 统计解决方案
› http://code.google.com/mobile/analytics/
WWDC
› https://developer.apple.com/wwdc/
Design Guides and Resources
› https://developer.apple.com/design/
Transcripts of WWDC sessions
› http://asciiwwdc.com
Cocoa with Love
› http://cocoawithlove.com/
Cocoa Dev Central
› http://cocoadevcentral.com/
NSHipster
› http://nshipster.com/
Style Guides
› Google Objective-C Style Guide
› NYTimes Objective-C Style Guide
Useful Tools and Services
› Charles Web Debugging Proxy
› Smore
eggacher
V2EX  ›  iDev

一个递归方法锁的问题

  •  
  •   eggacher · Feb 18, 2014 · 3542 views
    This topic created in 4621 days ago, the information mentioned may be changed or developed.
    我在用CFSocket写一个读取tcp发送过来的文件的程序;
    在CFStream读取的时候遇到了一点问题:

    void readStream(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) {

    UInt8 buff[1024];
    CFIndex index = CFReadStreamRead(stream, buff, 1024);
    if (index != 0 && index != 0 ) {

    //继续读取数据
    [_receiveData appendBytes:buff length:1024];

    }else{

    //读取完毕
    [refToSelf didFinishReceiveData:_receiveData];

    CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    CFReadStreamClose(stream);
    CFRelease(stream);
    }
    }

    这里算是一个递归函数,每次进来CFReadStreamRead一下1024个字节,然后根据读到的字节数判断有没有读到文件末尾;如果不是末尾,将字节流添加到一个NSMutableData中。

    这里出现问题了,CFReadStreamRead(stream, buff, 1024)的回调方法是本方法,
    因为每次进来的时候,先执行了CFReadStreamRead,导致本方法可能会被执行了无数遍;而后面的代码执行顺序不一定,导致append的byte顺序是错乱的。

    iOS或C有类似方法锁一样的东西可以解决这个问题么?
    @synchronized试过了,没有用。
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   943 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 21:54 · PVG 05:54 · LAX 14:54 · JFK 17:54
    ♥ Do have faith in what you're doing.