2016-05-13 37 views
9

Ho due funzioni foo e bar che dovrebbero escludersi a vicenda poiché operano sugli stessi dati. Tuttavia, foo duplica un sacco di codice da bar, quindi mi piacerebbe refactoring foo per effettuare una chiamata a bar.Funzioni che si escludono reciprocamente chiamando l'un l'altro

Questo è un problema perché non è possibile utilizzare un singolo mutex per entrambe le funzioni, perché in tal caso foo si bloccherebbe quando chiama bar. Quindi piuttosto che "mutuamente esclusivo" voglio solo "escludermi a vicenda da diversi thread".

Esiste uno schema per l'implementazione? Sto usando C++ e sto bene con C++ 14/boost se ho bisogno di qualcosa come shared_mutex.

+0

Utilizzando un 'üerhaps std :: mutex'? –

+0

Passa il mutex come parametro alla sezione refactored del codice condiviso. –

+2

@ πάνταῥεῖ: "üerhaps" suona come una malattia che porti a casa da una vacanza, o forse da un concerto metal. –

risposta

20

Definire una funzione privata "sbloccato" e l'uso che sia foo e bar:

void bar_unlocked() 
{ 
    // assert that mx_ is locked 
    // real work 
} 

void bar() 
{ 
    std::lock_guard<std::mutex> lock(mx_); 
    bar_unlocked(); 
} 

void foo() 
{ 
    std::lock_guard<std::mutex> lock(mx_); 
    // stuff 
    bar_unlocked(); 
    // more stuff 
} 
+0

Sì, soluzione molto migliore rispetto a mutex ricorsivo terribile. – SergeyA

+0

abbastanza ovvio (aveva la stessa idea, ma era troppo tardi) – Walter

4

un altro modo - questo ha il vantaggio che si può dimostrare che il blocco è stata presa:

void bar_impl(std::unique_lock<std::mutex> lock) 
{ 
    assert(lock.owns_lock()); 
    // real work 
} 

void bar() 
{ 
    bar_impl(std::unique_lock<std::mutex>(mx_)); 
} 

void foo() 
{ 
    // stuff 
    bar_impl(std::unique_lock<std::mutex>(mx_)); 
    // more stuff 
} 

Motivazione:

std::mutex non è (incaricato dalla standard per essere) mobile, ma un std::unique_lock<std::mutex> è. Per questo motivo, possiamo spostare un blocco in un chiamato e restituirlo a un chiamante (se necessario).

Ciò ci consente di provare la proprietà della serratura in ogni fase di una catena di chiamate.

Inoltre, una volta che l'ottimizzatore viene coinvolto, è probabile che tutto il movimento di blocco sarà ottimizzato. Questo ci dà il meglio di entrambi i mondi: proprietà dimostrabile e prestazioni massime.

Un esempio più completo:

#include <mutex> 
#include <cassert> 
#include <functional> 

struct actor 
{ 
    // 
    // public interface 
    // 

    // perform a simple synchronous action 
    void simple_action() 
    { 
    impl_simple_action(take_lock()); 
    } 

    /// perform an action either now or asynchronously in the future 
    /// hander() is called when the action is complete 
    /// handler is a latch - i.e. it will be called exactly once 
    /// @pre an existing handler must not be pending 
    void complex_action(std::function<void()> handler) 
    { 
    impl_complex_action(take_lock(), std::move(handler)); 
    } 

    private: 

    // 
    // private external interface (for callbacks) 
    // 
    void my_callback() 
    { 
    auto lock = take_lock(); 
    assert(!_condition_met); 
    _condition_met = true; 
    impl_condition_met(std::move(lock)); 
    } 


    // private interface 

    using mutex_type = std::mutex; 
    using lock_type = std::unique_lock<mutex_type>; 

    void impl_simple_action(const lock_type& lock) 
    { 
    // assert preconditions 
    assert(lock.owns_lock()); 
    // actions here 
    } 

    void impl_complex_action(lock_type my_lock, std::function<void()> handler) 
    { 
    _handler = std::move(handler); 
    if (_condition_met) 
    { 
     return impl_condition_met(std::move(my_lock)); 
    } 
    else { 
     // initiate some action that will result in my_callback() being called 
     // some time later 
    } 
    } 

    void impl_condition_met(lock_type lock) 
    { 
     assert(lock.owns_lock()); 
     assert(_condition_met); 
     if(_handler) 
     { 
     _condition_met = false; 
     auto copy = std::move(_handler); 
     // unlock here because the callback may call back into our public interface 
     lock.unlock(); 
     copy(); 
     } 
    } 



    auto take_lock() const -> lock_type 
    { 
    return lock_type(_mutex); 
    } 


    mutable mutex_type _mutex; 

    std::function<void()> _handler = {}; 
    bool _condition_met = false; 
}; 

void act(actor& a) 
{ 
    a.complex_action([&a]{ 
    // other stuff... 
    // note: calling another public interface function of a 
    // during a handler initiated by a 
    // the unlock() in impl_condition_met() makes this safe. 
    a.simple_action(); 
    }); 

} 
+0

Il 'more stuff' ancora in esecuzione con il mutex bloccato? 'sposta un lucchetto in un callee e restituiscilo a un chiamante' Un'altra opzione passa il riferimento. – jingyu9575