iOS多線程的初步研究(九)-- dispatch源

原文地址  http://www.cnblogs.com/sunfrog/p/3243230.html


dispatch源(dispatch source)和RunLoop源概念上有些類似的地方,而且使用起來更簡單。要很好地理解dispatch源,其實把它看成一種特別的生產消費模式。dispatch源好比生產的數據,當有新數據時,會自動在dispatch指定的隊列(即消費隊列)上運行相應地block,生產和消費同步是dispatch源會自動管理的。

dispatch源的使用基本爲以下步驟:

1. dispatch_source_t source = dispatch_source_create(dispatch_source_type, handler, mask, dispatch_queue); //創建dispatch源,這裏使用加法來合併dispatch源數據,最後一個參數是指定dispatch隊列

2. dispatch_source_set_event_handler(source, ^{ //設置響應dispatch源事件的block,在dispatch源指定的隊列上運行

  //可以通過dispatch_source_get_data(source)來得到dispatch源數據

});

3. dispatch_resume(source); //dispatch源創建後處於suspend狀態,所以需要啓動dispatch源

4. dispatch_source_merge_data(source, value); //合併dispatch源數據,在dispatch源的block中,dispatch_source_get_data(source)就會得到value。

是不是很簡單?而且完全不必編寫同步的代碼。比如網絡請求數據的模式,就可以這樣來寫:

    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD00dispatch_get_global_queue(00));

    dispatch_source_set_event_handler(source, ^{

        dispatch_sync(dispatch_get_main_queue(), ^{

    //更新UI

        });

    });

    dispatch_resume(source);

    dispatch_async(dispatch_get_global_queue(00), ^{

   //網絡請求

        dispatch_source_merge_data(source, 1); //通知隊列

    });

dispatch源還支持其它一些系統源,包括定時器、監控文件的讀寫、監控文件系統、監控信號或進程等,基本上調用的方式原理和上面相同,只是有可能是系統自動觸發事件。比如dispatch定時器:

dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER00, queue);

dispatch_source_set_timer(timerdispatch_walltime(NULL0), 10*NSEC_PER_SEC, 1*NSEC_PER_SEC); //每10秒觸發timer,誤差1秒

dispatch_source_set_event_handler(timer, ^{

  //定時處理

});

dispatch_resume(timer);

其它情況的dispatch源就不再一一舉例,可參看官網有具體文檔: https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW1

 

最後,dispatch源的其它一些函數大致羅列如下:

uintptr_t dispatch_source_get_handle(dispatch_source_t source); //得到dispatch源創建,即調用dispatch_source_create的第二個參數

unsignedlong dispatch_source_get_mask(dispatch_source_t source); //得到dispatch源創建,即調用dispatch_source_create的第三個參數

void dispatch_source_cancel(dispatch_source_t source); //取消dispatch源的事件處理--即不再調用block。如果調用dispatch_suspend只是暫停dispatch源。

long dispatch_source_testcancel(dispatch_source_t source); //檢測是否dispatch源被取消,如果返回非0值則表明dispatch源已經被取消

void dispatch_source_set_cancel_handler(dispatch_source_t source, dispatch_block_t cancel_handler); //dispatch源取消時調用的block,一般用於關閉文件或socket等,釋放相關資源

void dispatch_source_set_registration_handler(dispatch_source_t source, dispatch_block_t registration_handler); //可用於設置dispatch源啓動時調用block,調用完成後即釋放這個block。也可在dispatch源運行當中隨時調用這個函數。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章