boost lock_guard

I need a lock guard as bellow,if my code was used by multithread,the lock would work,but do nothing for singlethread.I used a bool param to enable this feature.
Is there an implemention in boost?more stable and more strong?
thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template<typename Mutex>
class bool_lock_guard
{
private:
	Mutex& m;
	bool m_use;
public:
	explicit bool_lock_guard(bool use,Mutex& m_):
	m(m_),m_use(use)
	{
		if(m_use) m.lock();
	}
	~bool_lock_guard()
	{
		if(m_use) m.unlock();
	}
};
I don't know about boost. Have you considered a simple ifdef?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <mutex>

int main()
{
    #ifdef MULTITHREADING
        std::mutex mute;
        std::lock_guard guard(mute);
    #endif
    
    return 0;
}

Last edited on
In my opinion, a runtime cost of conducting the check (which I would expect to be comparable to the cost of simply locking the mutex anyway), plus the dev/maintenance cost of having the more complex code, outweighs the cost of just always having the lock guard. Just always have the lock guard. Simple, fast, easy.

While I'm here, the C++ standard library has its own mutexes and lock guards. No need to use boost.
Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <mutex>
#include <type_traits>
#include <vector>

static constexpr bool USE_MUTEX =
#ifdef MULTITHREADED
   true ;
#else // !defined MULTITHREADED
   false ;
#endif // MULTITHREADED ;

namespace utility
{
    struct fake_mutex
    {
        constexpr void lock() const noexcept {}
        constexpr void unlock() const noexcept {}
        constexpr bool try_lock() const noexcept { return true ; }
    };

    using mutex = typename std::conditional< USE_MUTEX, std::mutex, utility::fake_mutex >::type ;
    using lock_guard = std::lock_guard<utility::mutex> ;
}

struct A // example usage
{
    void foo( int v )
    {
        utility::lock_guard lock(m) ;
        data.push_back(v) ;
    }

    utility::mutex m ;
    std::vector<int> data ;
};
Topic archived. No new replies allowed.