#include <mutex>
class ConcurrentQueue {
// This class contains a queue and contains functions push to the queue and pop from the queue done in a thread safe manner.
std::mutex m;
};
class Producer {
// This class contains several methods which take some ConcurrentQueue objects and then schedule tasks onto it.
public:
void func(ConcurrentQueue a) {}
};
class Consumer {
// This class contains several methods which take the same ConcurrentQueue objects and then remove the tasks and complete them one by one.
public:
void func(ConcurrentQueue a) {}
};
int main() {
// Here I want to generate the necessary ConcurrentQueue objects and then start threads for producer and consumer methods where I supply it with the required queue objects.
ConcurrentQueue a;
Producer b;
// :( Unfortunately I cannot pass in any of my ConcurrentQueue objects to the methods as apparantly I cannot copy transfer a mutex.
b.func(a); // This line gives compiler error saying the copy constructor is deleted.
return 0;
}
上面的代碼通過注釋解釋了整個情況。我如何更好地設計它以便能夠實作這一目標?
uj5u.com熱心網友回復:
如果您不希望您的 ConcurrentQueue 類是可復制的,那么不要按值傳遞它;改為使用傳遞參考(即型別const ConcurrentQueue &或引數ConcurrentQueue &)。
OTOH,如果您確實希望您的 ConcurrentQueue 類是可復制的(并且您應該仔細考慮允許復制 ConcurrentQueue 物件是否對您的目標有幫助或有害),您可以簡單地將復制建構式添加到您的 ConcurrentQueue 類中復制其他成員變數但不嘗試復制 std::mutex:
class ConcurrentQueue {
// This class contains a queue and contains functions push to the queue and pop from the queue done in a thread safe manner.
std::mutex m;
std::queue<int> q;
public:
ConcurrentQueue()
{
// default constructor
}
ConcurrentQueue(const ConcurrentQueue & rhs)
{
// serialize access to rhs.q so we can read its
// contents safely while copying them into this->q
const std::lock_guard<std::mutex> lock(const_cast<std::mutex &>(rhs.m));
q = rhs.q;
}
};
請注意,我還需要添加默認建構式,因為一旦您向類添加任何型別的建構式,編譯器將不再自動為您創建默認建構式。如果您使用的是 C 11 或更高版本,則可以ConcurrentQueue() = default;改為通過宣告默認建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504213.html
上一篇:我可以在不詢問偏移量的情況下從HTML表單中決議OffsetDateTime嗎?
下一篇:更改矢量時如何保持執行緒解開?C
