快速而肮脏的 Win32 解决方案将涉及 UI 线程中的临界区、文本缓冲区和计时器。
定义一些全局变量...
CRITICAL_SECTION bufferLock; // critical section (to be initialized somewhere)
char dataBuffer[65536]; // contains the data that will be sent to the form
int newdata = 0; // how much data we got (this variable must be atomic, int is ok)
char uiDataBuffer[65536]; // data available to the form
int overflow = 0; // just in case...
UI 线程计时器
void onTimer ()
{
if (overflow)
{
// handle this
}
else
if (newdata) // new data to display
{
// take the lock, copy the data and release the lock quickly
EnterCriticalSection(&bufferLock);
int dataread = newdata;
memcpy(uiDataBuffer, dataBuffer, dataread);
newdata = 0;
LeaveCriticalSection(&bufferLock);
// TODO: append the text in uiDataBuffer[] to your text control
}
}
从工作线程调用:
void sendData (char* data, int size)
{
EnterCriticalSection (&bufferLock);
if(size+newdata > 65536)
overflow = 1;
else
{
memcpy(dataBuffer+newdata, data, size);
newdata += size;
}
LeaveCriticalSection (&bufferLock);
}
代码未经测试。缓冲区大小和定时器频率有待调整。
通过使用 PostMessage()(带有自定义消息)向 UI 发出新数据可用的信号,可以避免使用计时器轮询缓冲区。
如果性能是一个问题,生产者和消费者线程之间的数据交换也可以通过无锁 FIFO 队列非常有效地执行。
PostMessage() 单独不是解决方案在线程之间交换数据。