(i) Title
The data is downloaded on the network and then stored on the hard disk. The simple thing to do is to download a piece and write it to the hard disk, then download it and write it to the hard disk.
Disadvantage: The download and write are serial operations that need to be downloaded before they can be written to the hard disk.
Improvement: Let two threads in parallel, set the buffer, in the form of semaphores.
Download the thread, as long as the buffer is free to download, after the download is complete to tell the write thread buffer has data.
Write thread, as long as the buffer has data to write, after writing to tell the download thread buffer is free.
The code is as follows:
Class Thread {public:thread (void (*work_func)); ~thread (); void Start (); void Abort ();}; Class Semaphore {public:semaphore (int count, int max_count); ~semaphore (); void unsignal (); Count--void Signal (); Count++};class Mutex {Public:waitmutex (); ReleaseMutex ();};/ /If using mutexes, the download and storage threads will not work at the same time, so semaphore is a better choice of # define Buffer_count 100Block G_buffer[buffer_count]; Thread G_threada (Proca); Thread g_threadb (PROCB); Semaphore g_sefull (0, Buffer_count); A start buffer is available for storage semaphore G_seempty (Buffer_count, Buffer_count); The buffer space at the beginning is buffer_count, and the entire buffer is populated with bool G_downloadcomplete for the downloaded data; Download task completed int in_index = 0; The downloaded data from where the buffer begins to populate int out_index = 0; The stored data from where the buffer begins to extract void Main () {g_downloadcomplete = False;g_threada.start (); G_threadb.start ();} void Proca () {while (true) {g_seempty.unsignal (); First get a free space to download the data to populate G_downloadcomplete = getblockfromnet (G_buffer + in_index); Fill In_index = (in_index + 1)% Buffer_count; Update index g_sefull.signal (); Hint that the storage thread can work if (g_downloadcomplete) break; When the task is fully downloaded, the process can end with}}void PROCB () {while (true) {g_sefull.unsignal (); Data is available for storage writeblocktodisk (G_buffer + out_index) when querying; Storage Out_index = (out_index + 1)% Buffer_count; Update index g_seempty.signal (); Return free space to buffer if (g_downloadcomplete && out_index = = in_index) break; When the task is fully downloaded and all the data is stored on the hard disk, the process can end}}
1.10 Two-thread efficient download