一个快速而脏的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()不是线程间交换数据的解决方案。
将次要线程的自定义消息发布到对话框。 – ildjarn 2012-01-04 23:57:14