2008年6月18日星期三

Resources loading

最近完成了漸進裝載系統 (Progressive resource loading) 的設計與實作.
現階段能夠以多緒形式載入 Jpeg 和 Png



要達到多緒, 首要分開載入和使用中的資料.
函式 load() 會把 istream 中的資料解碼到 loader 裏的私有緩衝區之中, 這時候 LoadingState 為 Loading.
當一定數量的資料已解碼而又可以顯示出來, load() 會返回 LoadingState = PartialLoaded, 這時候你可以乎叫 commit() 把 loader 中的緩衝抄到 resource 去.
請注意 load(), commit() 和 getLoadingState() 好有可能在不同的執行緒中執行, 因此 loader 裏的緩衝區和 LoadingState 成員都要用 Mutex 來保護.



有一點值得討論的就是 load() 這函式.
現在的設計須要用者不停地乎叫 load() 直到它返回 Loaded 或 Aborted. 但我曾經考慮過使用事件 (Event) 來通知用者現在的 LoadingState 從而只需乎叫 load() 一次. 接著當我試圖實作 cancel() 這函式時, 問題出現了; 我得建造另一個事件來控制 load() 內部的循環何時跳出.
實在不好, 複雜跳進來了...還要處理令人頭痛的多緒同步哩! 想起 Pull Xml 帶給我的啟示, 原來只要把 load() 內的循環交給用者來定義, 一切都簡單得多.
再細心的想, 如果用者希望一幅圖像載入了第一個漸進後便去開始載入另一幅圖像的話, 用事件的作法是行不通的 (或變得異常複雜). 所以這個新的設計不止簡單, 還非常靈活. 我又一次體會到什麼是 Less is more, There is No CODE that is more flexible than NO Code!.

2 則留言:

  1. 如果 buffer 不會同時在 app , loader thread 同時使用, 也許可以再簡化點來增加 performance

    LoadingState <- change to Atomic integer something
    buffer <- don't have to protect by mutex any more

    回覆刪除
  2. Thanks for your comment, you are the first one!

    Yes, if the loader is going to support background loading only but not progressive loading. Since the loader is already stopped while the user going to call commit(). And the concrete implementation of IResourceLoader have the freedom of how to define the LoadingState variable.

    回覆刪除