I had finished the code optimzed. Let's see the code first.
#include <QMutex>
#include <QQueue>
#include <QWaitCondition>
#include <QByteArray>
QThread *rxthread = new QThread;
QThread *writethread = new QThread;
QMutex mutex;
QQueue<QByteArray> dataQueue;
void Widget::ReadingProc()
{
DWORD RxBytes;
DWORD dwRXBytes;
// uchar rx_char[99999];
char rx_char[99999];
while (bContinue)
{
FT_GetQueueStatus(ftHandle, &RxBytes);
if ((ftStatus == FT_OK) && (RxBytes > 0))
{
ftStatus = FT_Read(ftHandle, &rx_char, RxBytes, &dwRXBytes);
if (ftStatus == FT_OK)
{
// QByteArray data(reinterpret_cast<const char *>(rx_char), dwRXBytes);
QByteArray data(rx_char, dwRXBytes);
QMutexLocker locker(&mutex);
dataQueue.enqueue(data);
}
else
{
QMessageBox::warning(NULL, "test", "ReadingProc ERROR!");
}
}
}
}
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(rxthread, &QThread::started, [=]() {
ReadingProc();
rxthread->exit();
});
connect(writethread, &QThread::started, [=]() {
qDebug() << "writethread start!";
while (true) {
QByteArray data;
{
QMutexLocker locker(&mutex);
if (dataQueue.isEmpty())
continue;
data = dataQueue.dequeue();
}
// 将QByteArray转换为16进制字符串
QString hexData = data.toHex();
//从QT获取文件名称
QString filepath;
filepath = ui->PathEdit->text();
QFile file(filepath);
// file.open(QIODevice::WriteOnly);
// QTextStream out(&file);
// QFile file("data.dat");
if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {
QTextStream out(&file); // 使用QTextStream进行文件写入
out << hexData; // 写入16进制字符串
file.close(); // 关闭文件
}
}
});
connect(rxthread, &QThread::finished, [=]() {
qDebug() << "rxthread finish!";
});
connect(writethread, &QThread::finished, [=]() {
qDebug() << "writethread finish!";
});
}
Widget::~Widget()
{
writethread->exit();
delete ui;
}
Now I set up two threads, one for get data from USB2.0 and another transfer the data to the file.
There are two points, one is QMutex and another is QQueue.
Becase there are two threads, in these threads, use QQueue<QByteArray> dataQueue to transfer data between them and use QMutex mutex to avoid thread conflict.
QMutexLocker locker(&mutex);
This is a locker to avoid thread conflict, QMutexLocker locker(&mutex) is better than mutex.lock() and mutex.unlock(). By using QMutexLocker locker(&mutex) to lock thread and unlock at finish {}.
if (ftStatus == FT_OK)
{
// QByteArray data(reinterpret_cast<const char *>(rx_char), dwRXBytes);
QByteArray data(rx_char, dwRXBytes);
QMutexLocker locker(&mutex);
dataQueue.enqueue(data);
}
For example, this thread will unlock after dataQueue.enqueue(data).
dataQueue.enqueue(data);
This code will add data at the end of dataQueue.
dataQueue.isEmpty()
This code is judge where the dataQueue is empty, if is empty then will return false.
data = dataQueue.dequeue();
This code will remove and return the first element to data form dataQueue.
Then I will try to use golang to transfer data in order to convenient for the next step of processing.