2011-04-12 47 views

回答

12

您可能需要使用LLVM Clang (available on Ubuntu)編譯器來獲取塊(目前我認爲這在gcc中沒有,但我一直沒有跟上gcc,所以我可能是錯的。)

正在努力將libdispatch (home for the open source libdispatch)移植到Linux。到目前爲止,大部分努力似乎都在Debian上,但其他一些發行版上也有一些。看到這些討論主題:

+0

謝謝!許多谷歌搜索只爲我造成混亂。 – mummey 2011-04-13 18:47:49

+0

不客氣!有時候,Google可能很難找到類似這樣的東西,特別是在一個不熟悉的主題上。 – 2011-04-13 21:28:31

+0

只要你可以使用鏗鏘聲,我就可以在ubuntu natty上[很高興地使用gcd](http://chris.mowforth.com/installing-grand-central-dispatch-on-linux)。 – 2011-07-31 10:08:07

-2

不是使用塊,而是使用C++ lambda。他們用C++玩的更好,隱藏的魔法也更少。

我不喜歡這樣寫道:

/// Dispatch a function object to a queue. 
template<class F> 
static void dispatch_async_function(dispatch_queue_t queue, F f) { 
    struct context_t { 
     using function_type = F; 

     context_t(function_type&& f) noexcept 
     : _f(std::move(f)) 
     {} 

     static void execute(void* p) noexcept { 
      auto context = reinterpret_cast<context_t*>(p); 
      if (context) { 
       try { 
        context->_f(); 
       } 
       catch(...) { 
        // error processing here 
       } 
       delete context; 
      } 
     } 

    private: 
     function_type _f; 
    }; 

    dispatch_async_f(queue, new context_t<F>(std::move(f)), &context_t<F>::execute); 
} 

如果你需要確保一些共享資源所在的呼叫發生(如對象上的回調是由共享指針保持活力)前:

/// Dispatch a function object to a queue. Only execute the function if the tie 
/// locks successfully. 
template<class F> 
static void dispatch_async_tied_function(dispatch_queue_t queue, std::weak_ptr<void> tie, F f) { 
    struct context_t { 
     using function_type = F; 

     context_t(function_type&& f) noexcept 
     : _f(std::move(f)) 
     {} 

     static void execute(void* p) noexcept { 
      auto context = reinterpret_cast<context_t*>(p); 
      auto lock = _tie.lock(); 
      if (context && tie) { 
       try { 
        context->_f(); 
       } 
       catch(...) { 
        // error processing here 
       } 
       delete context; 
      } 
     } 

    private: 
     function_type _f; 
     std::weak_ptr<void> _tie; 
    }; 

    dispatch_async_f(queue, new context_t<F>(std::move(f)), &context_t<F>::execute); 
} 

叫他們這樣

dispatch_function(queue, []() { something(); }); 

或...

dispatch_tied_function(_myQueue, shared_from_this(), [this]() { somethingOnThis(); }); 
0

使用clang-3.4。

  • 命令和apt-get安裝libdispatch-dev的
  • 命令和apt-get安裝libblocks運行時-dev的
  • 編譯-fblocks
  • 鏈接與-lBlocksRuntime -ldispatch
相關問題