Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C++: Am I using this mutex correctly?

I feel that it can be done in a better way than this.

    #include <functional>

    #include <thread>

    #include <mutex>

    #include <chrono>

    #include <iostream>

    std::mutex m;

    void f(int& n)

    {

        m.lock();

        ++n;

        m.unlock();

        std::this_thread::sleep_for( std::chrono::seconds(1) );

    }

    int main()

    {

        int n(0);

        std::function<void()> h(std::bind(f, std::ref(n)));

        std::thread f1(h);

        f1.join();

        std::this_thread::sleep_for( std::chrono::seconds(2) );

        std::cout << n; // 1

    }

Is this a correct way of using mutexes? I am new to this by the way.

1 Answer

Relevance
  • Anonymous
    8 years ago
    Favorite Answer

    // Read this 8 PAGE tutorial

    // http://www.justsoftwaresolutions.co.uk/threading/m...

    //

    // removed unneeded headers

    #include <iostream>

    #include <mutex>

    #include <thread>

    // internally linked mutex

    static std::mutex m_n;

    void f(int& n)

    {

    m_n.lock();

    ++n;

    m_n.unlock();

    std::this_thread::sleep_for(std::chrono::seconds(1));

    }

    // mutex released when scope is destroyed

    void fs(int& n)

    {

    std::lock_guard <std::mutex> m(m_n);

    ++n;

    }

    int main()

    {

    int n(0);

    std::thread t_f1(fs, std::ref(n));

    std::thread t_f2(f, std::ref(n));

    t_f1.join();

    t_f2.join();

    std::this_thread::sleep_for (std::chrono::seconds(2));

    std::cout << n; // 1

    }

Still have questions? Get your answers by asking now.