In C++Builder(C++11), use timed_mutex.

Posted by on in Programming

In C++11, mutex is attached as a standard library.
Of course, it can also be used in C++Builder.

There are mutex,recursive_mutex,timed_mutex,recursive_timed_mutex.
I tried timed_mutex this time.
timed_mutex supports lock acquisition timeout function.
Timeout uses chrono.

_tmnutex_test.h
struct _tmnutex_test
{
    std::timed_mutex f_mutex_;
    std::vector<String> f_v1_;
    void add(String str1_)
    {
        //Wait 3 seconds.
        if (!f_mutex_.try_lock_for(std::chrono::seconds(3)))
        {
            throw Exception("time out 'try_lock_for'");
        }
        //Sleep for 3 seconds after successful lock.
        std::this_thread::sleep_for(std::chrono::seconds(3));
        f_v1_.push_back(str1_);
        f_mutex_.unlock();
    };
};

This is processing to wait 3 seconds for timeout.
Then, three seconds sleep processing.
So If the lock succeeds, it is push_back() to the vector.

Use call this class in the form button of FireMonkey C++ project.

main_form1.cpp
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    _tmnutex_test tmnutex1_;
    std::vector<std::thread> th1_;
    for (int i = 0; i < 10; ++i)
    {
        th1_.push_back(std::thread([&tmnutex1_, i, &th1_]()
            {
                try
                {
                    tmnutex1_.add(i);
                }
                catch(Exception& ex1)
                {

                }
            })
        );
    }

    for (auto& th_: th1_)
    {
        th_.join();
    }

    for (auto& s_: tmnutex1_.f_v1_) {
        Memo1->Lines->Append(s_);

    }
}

Thread processing that timed out here is an exception.
So, it is not push_back() to vector.
Ten threads were created,There is both processing and exception handling is push_back() to vector.

The lock on timed_mutex timed out, so we handled the exception.

 



About
Gold User, No rank,
Delphi / C++Builder blogger

Comments

Check out more tips and tricks in this development video: