Ericzhang88120
Ericzhang88120

Reputation: 59

mutex lock in multi-thread can I use several mutex locks

I want to implement a function that I create 5 pairs threads(one pair means one thread write and the other read and both of the threads share one list (5 lists in this scenario). Do I need to create five mutex locks? How to declare them? In global area?

Upvotes: 2

Views: 280

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Do I need to create five mutex locks?

Depends on your data structure. If you have five different data objects to access safely from five associated thread pairs, you'll need five, if all threads access only one data object you'll need only one.

How to declare them? In global area?

Encapsulate your data object, the mutex and (writing) thread functions in a class. I'd say you'll not need another reading thread, that's the one that calls run usually, or any other that'll have access to instance of this class.

class MyAsynchDataProvider
{
public:

    void run()
    {
        writeThread = std::thread(writeDataFunc,this);
    }

    MyDataStruct getSafeDataCopy()
    {
        std::lock_guard lock(dataGuard);
        return data;
    }

private:
    std::mutex dataGuard;
    MyDataStruct data;

    std::thread writeThread;

    static void writeThreadFunc(MyDataWorker* thisPtr)
    {
        // ...
        std::lock_guard lock(thisPtr->dataGuard);
        // Write to thisPtr->data member
    }
};

Upvotes: 1

Related Questions