Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter05/02_mutex/main.cpp #14

Open
zoldaten opened this issue Oct 30, 2023 · 1 comment
Open

Chapter05/02_mutex/main.cpp #14

zoldaten opened this issue Oct 30, 2023 · 1 comment

Comments

@zoldaten
Copy link

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
Copy link
Owner

apolukhin commented Feb 17, 2024

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants