信号量与多线程 2
第十七课
多文件下载
int DownloadSingleFile(const char *server, const char *path);
int DownloadAllFiles(const char *server,
const char *files[],
int n) {
int totalBytes = 0;
Semaphore lock = 1;
for (int i = 0; i < n; i++) {
ThreadNew("...", DownloadHelper, 4
server, files[i], &totalBytes, lock);
}
return totalBytes;
}
void DownloadHelper(const char *server,
const char *path,
int *numBytesp,
Semaphore lock) {
int bytesDownloaded = DownloadSingleFile(server, path);
SemaphoreWait(lock); // why not put SW before bytesDownloaded
(*numBytesp) += bytesDownloaded;
SemaphoreSignal(lock);
}Last updated