本文主要是介绍双线程高效下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
编程之美 10
// 不确定对否
class Semaphore {
public:Semaphore(int count_, int max_count_) : count(count_), max_count(max_count_) {}void signal() {std::unique_lock<std::mutex> lock(mtx);while (count == max_count) {cv.wait(lock);}count++;cv.notify_one();}void unsignal() {std::unique_lock<std::mutex> lock(mtx);while (count == 0) {cv.wait(lock);}count--;cv.notify_one();}private:std::mutex mtx;std::condition_variable cv;int count;int max_count;
};const int BUFFER_COUNT = 100;
int g_buffer[BUFFER_COUNT];Semaphore g_seFull(0, BUFFER_COUNT);
Semaphore g_seEmpty(BUFFER_COUNT, BUFFER_COUNT);
bool g_downloadComplete;
int in_index = 0;
int out_index = 0;bool getBlockFromNet(int* in_block);
bool writeBlockToDisk(int* out_block);
void procA() {while (true) {g_seEmpty.unsignal();g_downloadComplete = getBlockFromNet(g_buffer + in_index);in_index = (in_index + 1) % BUFFER_COUNT;g_seFull.signal();if (g_downloadComplete)break;}
}void procB() {while (true) {g_seEmpty.unsignal();writeBlockToDisk(g_buffer + out_index);out_index = (out_index + 1) % BUFFER_COUNT;if (g_downloadComplete && out_index == in_index)break;}
}
std::thread g_threadA(procA);
std::thread g_threadB(procB);
void main() {g_downloadComplete = false;g_threadA.join();g_threadB.join();
}
这篇关于双线程高效下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!