Closed NanoPangBZ closed 9 months ago
The user is experiencing an issue where creating a SerialPort
object affects the static method SerialPort::getSerialPortList
. The proposed solution involves ensuring that the static list of serial ports is not improperly modified upon the creation of a SerialPort
object. The key is to maintain the integrity of the static list while allowing for thread-safe operations.
The reasoning for the solution includes:
_serialPortInfoList
is only populated once, to prevent changes to the list after the initial population.For SerialPort/SerialPort.cpp
:
void SerialPort::_refreshSerialPortInfoList()
{
static std::mutex listMutex;
std::lock_guard<std::mutex> lock(listMutex);
// Only populate the list if it's empty
if (_serialPortInfoList.empty()) {
// ... existing code to populate _serialPortInfoList ...
}
}
For main.cpp
:
#include <iostream>
#include <windows.h>
#include "SerialPort.h"
#include <vector>
static int serial_evt_handler(SerialPort::SerialPortEvent evt)
{
// ... existing code ...
}
int main()
{
// First call to getSerialPortList before creating SerialPort object
std::vector<SerialPort::SerialPortInfo> listBefore = SerialPort::getSerialPortList();
std::cout << "Ports before creating SerialPort object:" << std::endl;
for (const auto& portInfo : listBefore)
{
std::cout << portInfo.portName << std::endl;
}
// Create SerialPort object
SerialPort* serialPort = new SerialPort;
serialPort->registerEventHandler(serial_evt_handler, NULL);
serialPort->connect(29, 921600);
// Second call to getSerialPortList after creating SerialPort object
std::vector<SerialPort::SerialPortInfo> listAfter = SerialPort::getSerialPortList();
std::cout << "Ports after creating SerialPort object:" << std::endl;
for (const auto& portInfo : listAfter)
{
std::cout << portInfo.portName << std::endl;
}
// Compare the lists and output the result
bool listsMatch = (listBefore == listAfter);
std::cout << "The lists of serial ports match: " << (listsMatch ? "YES" : "NO") << std::endl;
// Clean up and exit
delete serialPort;
return 0;
}
By implementing these changes, we should be able to resolve the issue reported by the user. The main.cpp
code will help us verify that the static list of serial ports remains unchanged after creating a SerialPort
object, which would confirm that the issue has been fixed.
new一个SerialPort对象后会导致静态方法SerialPort::getSerialPortList出现问题。