gpt4 book ai didi

c++ - Qt moveToThread() vs 调用新线程我们什么时候使用每个线程

转载 作者:可可西里 更新时间:2023-11-01 18:15:19 24 4
gpt4 key购买 nike

我们什么时候在线程应用程序中使用每个函数调用。给定在同一个类中定义的两个函数 fun1() 和 fun2() 处理将数据读/写到缓冲区(队列操作)。实现多线程就这些。我们将不得不在单独的线程中运行这两个函数。现在假设第一个函数 read 在其线程开始时被调用。

is it better to use moveTothread ( second thread)for function write at the start of the first functions thread

或者

define the second function in a new thread class and call that thread at the start of the first thread.

最佳答案

就像 Piotr 回答的那样,您真的应该看看他建议的链接。
据我了解您的问题,这应该可以解决您的问题。
这是该博客的简化代码:

class Producer  
{
public:
Producer();

public slots:
void produce()
{ //do whatever to retrieve the data
//and then emit a produced signal with the data
emit produced(data);
//if no more data, emit a finished signal
emit finished();
}

signals:
void produced(QByteArray *data);
void finished();
};

class Consumer
{
public:
Consumer();

public slots:
void consume(QByteArray *data)
{
//process that data
//when finished processing emit a consumed signal
emit consumed();
//if no data left in queue emit finished
emit finished();
}
};

int main(...)
{
QCoreApplication app(...);

Producer producer;
Consumer consumer;

producer.connect(&consumer, SIGNAL(consumed()), SLOT(produce()));
consumer.connect(&producer, SIGNAL(produced(QByteArray *)), SLOT(consume(QByteArray *));

QThread producerThread;
QThread consumerThread;
producer.moveToThread(&producerThread);
consumer.moveToThread(&consumerThread);

//when producer thread is started, start to produce
producer.connect(&producerThread, SIGNAL(started()), SLOT(produce()));

//when consumer and producer are finished, stop the threads
consumerThread.connect(&consumer, SIGNAL(finished()), SLOT(quit()));
producerThread.connect(&producer, SIGNAL(finished()), SLOT(quit()));

producerThread.start();
consumerThread.start();

return app.exec();
}

关于c++ - Qt moveToThread() vs 调用新线程我们什么时候使用每个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5152609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com