[英]how to make lock free producer consumer thread exchange more exception safe with QThreads
我對這個否則很好的例子的抱怨是: http : //blog.qt.digia.com/blog/2006/12/04/threading-without-the-headache/是它在交換裸露的指針並且沒有使用Qt :: QueuedConnection。
編輯:這是上面鏈接顯示的代碼片段(以防鏈接在這篇文章之前掉線)
// create the producer and consumer and plug them together
Producer producer;
Consumer consumer;
producer.connect(&consumer, SIGNAL(consumed()), SLOT(produce()));
consumer.connect(&producer, SIGNAL(produced(QByteArray *)), SLOT(consume(QByteArray *)));
// they both get their own thread
QThread producerThread;
producer.moveToThread(&producerThread);
QThread consumerThread;
consumer.moveToThread(&consumerThread);
// go!
producerThread.start();
consumerThread.start();
如果我在生產者中使用unique_ptr,當我調用產生的信號時將其釋放,然后將裸指針直接放入連接的消耗插槽中的另一個唯一指針中,那會更安全。 特別是在經過一些維護后,程序員可以使用代碼了;)
void calculate()
{
std::unique_ptr<std::vector<int>> pi(new std::vector<int>());
...
produced(pi.release());
//prodiced is a signal, the connected slot destroys the object
//a slot must be connected or the objects are leaked
//if multiple slots are connected the objects are double deleted
}
void consume(std::vector<int> *piIn)
{
std::unique_ptr<std::vector<int>> pi(piIn);
...
}
這仍然有幾個主要問題:-當插槽未連接時,我不能防止泄漏-如果要連接多個插槽,則不能防止雙重刪除(如果編程的話,這對於程序員是一個邏輯錯誤發生了,但我想檢測出來)-我不太了解Qt的內部工作原理,以確保在傳輸過程中沒有泄漏。
如果我要使用共享指針const,它將解決我所有的問題,但速度會變慢,據我所知,我必須按如下所述在元對象系統中注冊它: http : //qt-project.org/ doc / qt-4.8 / qt.html#ConnectionType-enum這是個好主意嗎?
有我沒有想到的更好的方法嗎?
您不應該在期望插槽破壞它們的情況下在信號中傳遞指針,因為插槽可能不可用。
而是傳遞const引用,以允許插槽復制對象。 如果您使用Qt的容器類,這不會影響性能,因為Qt的容器類實現了寫時復制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.