網絡下載文件寫入硬碟。串行方式:下一塊 → 寫一塊,效率低。
改進:雙線程並行,緩衝區 + 信號量同步。
ForDownload:空閒槽位數 (初始 MAX)ForWrite:可寫數據塊數 (初始 0)// 下載線程
while (true) {
ForDownload.wait(); // 等待空位
isDone = GetBlockFromNet(buf[in_idx]);
in_idx = (in_idx + 1) % MAX;
ForWrite.signal(); // 通知有數據
if (isDone) break;
}
// 寫入線程
while (true) {
ForWrite.wait(); // 等待數據
WriteBlockToDisk(buf[out_idx]);
out_idx = (out_idx + 1) % MAX;
ForDownload.signal(); // 釋放空位
if (isDone && in_idx == out_idx) break; // 全部寫完
}
#define MAX_COUNT 1000
Block g_Buffer[MAX_COUNT];
Thread g_Download(ProcA), g_Write(ProcB);
Semaphore ForDownload(MAX_COUNT, MAX_COUNT);
Semaphore ForWrite(0, MAX_COUNT);
bool isDone = false;
int in_idx = 0, out_idx = 0;
void ProcA() { /* 下載邏輯 */ }
void ProcB() { /* 寫入邏輯 */ }
int main() {
g_Download.Start();
g_Write.Start();
// 等待線程結束...
return 0;
}
in_idx 生產者指針,out_idx 消費者指針isDone 且緩衝區清空 in_idx == out_idxGetBlockFromNet, WriteBlockToDisk 隔離業務邏輯Overlapped I/O / epoll 替代阻塞寫入