【发布时间】:2014-03-10 16:14:38
【问题描述】:
我目前正在尝试使用 boost::thread 和一个复选框来记录实时数据。当我选中该框时,日志记录线程开始。当我取消选中时,日志记录线程停止。当我反复且非常快速地检查/取消检查(程序崩溃、某些文件未记录等)时,就会出现问题。如何编写一个可靠的线程安全程序,在反复快速检查/取消检查时不会出现这些问题?我也不想使用 join() 因为这会暂时停止来自主线程的数据输入。在辅助线程中,我打开一个日志文件,从套接字读取到缓冲区,将其复制到另一个缓冲区,然后将此缓冲区写入日志文件。我在想也许我应该使用互斥锁进行读/写。如果是这样,我应该使用什么特定的锁?下面是一段代码sn-p:
//Main thread
if(m_loggingCheckBox->isChecked()) {
...
if(m_ThreadLogData.InitializeReadThread(socketInfo))//opens the socket.
//If socket is opened and can be read, start thread.
m_ThreadLogData.StartReadThread();
else
std::cout << "Did not initialize thread\n";
}
else if(!m_loggingCheckBox->isChecked())
{
m_ThreadLogData.StopReadThread();
}
void ThreadLogData::StartReadThread()
{
//std::cout << "Thread started." << std::endl;
m_stopLogThread = false;
m_threadSendData = boost::thread(&ThreadLogData::LogData,this);
}
void ThreadLogData::StopReadThread()
{
m_stopLogThread = true;
m_ReadDataSocket.close_socket(); // close the socket
if(ofstreamLogFile.is_open())
{
ofstreamLogFile.flush(); //flush the log file before closing it.
ofstreamLogFile.close(); // close the log file
}
m_threadSendData.interrupt(); // interrupt the thread
//m_threadSendData.join(); // join the thread. Commented out since this
temporarily stops data input.
}
//secondary thread
bool ThreadLogData::LogData()
{
unsigned short int buffer[1024];
bool bufferflag;
unsigned int iSizeOfBuffer = 1024;
int iSizeOfBufferRead = 0;
int lTimeout = 5;
if(!ofstreamLogFile.is_open())
{
ofstreamLogFile.open(directory_string().c_str(), ios::out);
if(!ofstreamLogFile.is_open())
{
return 0;
}
}
while(!m_stopLogThread)
{
try {
int ret = m_ReadDataSocket.read_sock(&m_msgBuffer.m_buffer
[0],iSizeOfBuffer,lTimeout,&iSizeOfBufferRead);
memcpy(&buffer[0],m_msgBuffer.m_buffer,iSizeOfBufferRead);
bufferflag = m_Buffer.setBuffer(buffer);
if(!bufferflag) return false;
object = &m_Buffer;
unsigned int data = object->getData();
ofstreamLogFile << data << std::endl;
boost::this_thread::interruption_point();
} catch (boost::thread_interrupted& interruption) {
std::cout << "ThreadLogData::LogData(): Caught Interruption thread." << std::endl;
StopReadThread();
} catch (...) {
std::cout << "ThreadLogData::LogData(): Caught Something." << std::endl;
StopReadThread();
}
} // end while()
}
【问题讨论】:
-
请编辑您的问题,而不是发布重复的问题。我只是在一个版本上浪费了时间,却不知道你取代了它。两次。
标签: c++ multithreading logging boost