一個快速而髒的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