我有一些項目,我有一個生產者線程將事件寫入緩衝區,另有一個消費者線程從緩衝區獲取事件。我的目標是優化這個東西爲單個雙核心機達到最大吞吐量。在生產者/消費者多線程環境中優化共享緩衝區
目前,我使用一些簡單的無鎖環緩衝器(無鎖是可能的,因爲我只有一個消費者和一個生產者線程,因此指針只是由單個線程更新)。
#define BUF_SIZE 32768
struct buf_t { volatile int writepos; volatile void * buffer[BUF_SIZE];
volatile int readpos;) };
void produce (buf_t *b, void * e) {
int next = (b->writepos+1) % BUF_SIZE;
while (b->readpos == next); // queue is full. wait
b->buffer[b->writepos] = e; b->writepos = next;
}
void * consume (buf_t *b) {
while (b->readpos == b->writepos); // nothing to consume. wait
int next = (b->readpos+1) % BUF_SIZE;
void * res = b->buffer[b->readpos]; b->readpos = next;
return res;
}
buf_t *alloc() {
buf_t *b = (buf_t *)malloc(sizeof(buf_t));
b->writepos = 0; b->readpos = 0; return b;
}
但是,這種實現還不夠快,應該進一步優化。我已經嘗試了不同的BUF_SIZE
值,並獲得了一些加速。另外,我已經在buffer
和readpos
之前移動了writepos
,在buffer
之後確保兩個變量都在不同的緩存行上,這也導致了一些速度。
我需要的是加速大約400%。你有什麼想法如何使用填充等東西來實現這一點?
「無鎖是可能的,因爲我只有一個消費者和一個生產者線程」 - 如果消費者和生產者線程發生衝突會發生什麼? – 2010-05-05 10:53:58
在忙碌中等待多少CPU? – 2010-05-05 10:56:40
@Marcelo Cantos:好點! – 2010-05-05 10:58:24