apolukhin / Boost-Cookbook

Online examples from "Boost C++ Application Development Cookbook":
http://apolukhin.github.io/Boost-Cookbook/
Boost Software License 1.0
402 stars 108 forks source link

Chapter05/02_mutex/main.cpp #14

Open zoldaten opened 11 months ago

zoldaten commented 11 months ago

i have trouble with compilation on raspberry pi but finally got in working. heres the code:

#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread.hpp>
#include <iostream>

namespace with_sync {

int shared_i = 0;
boost::mutex i_mutex;

void do_inc() {
    for (std::size_t i = 0; i < 30000; ++i) {
        int i_snapshot;
        {   // Critical section begin.
            boost::lock_guard<boost::mutex> lock(i_mutex);
            i_snapshot = ++shared_i;
        }   // Critical section end.
        std::cout<<i_snapshot<<std::endl;
        // Do some work with i_snapshot.
        // ...
        (void)i_snapshot;
    }
}

void do_dec() {
    for (std::size_t i = 0; i < 30000; ++i) {
        int i_snapshot;
        {   // Critical section begin.
            boost::lock_guard<boost::mutex> lock(i_mutex);
            i_snapshot = -- shared_i;
        }   // Critical section end.
            std::cout<<i_snapshot<<std::endl;
        // Do some work with i_snapshot.
        // ...
        (void) i_snapshot;
    }
}

int run() {
    boost::thread t1(&do_inc);
    boost::thread t2(&do_dec);

    t1.join();
    t2.join();

    assert(shared_i == 0);
    std::cout << "shared_i == " << shared_i;
}

} // namespace without_sync
int main() {
with_sync::run();
return 0; };

i have to add to CMakeLists.txt:

target_link_libraries(BoostTest ${Boost_LIBRARIES} -lpthread)
target_link_libraries(BoostTest ${Boost_LIBRARIES} -lboost_thread)

do these things double each other ? but without any of them get a error.

apolukhin commented 7 months ago

Yes, you have to link with boost_thread library if you are using any boost/thread* header.

The other libraries to link depend on the build system you are using. The modern cmake with modern Boost CMakeLists.txt should be able to propagate the -lpthread dependency. Try the following:

find_package(Boost REQUIRED COMPONENTS thread)
target_link_libraries(BoostTest Boost::thread)