多线程编程探索

来源:互联网 发布:淘宝音乐代码在线生成 编辑:程序博客网 时间:2024/05/16 08:53

一、编程之美之双线程高效下载

从网络上下载数据,单线程的工作模式是下载一块数据,写入硬盘,然后再下载,再写入硬盘,不断重复循环,直到文件下载完毕。

可对这个过程进行优化,采用双线程工作模式,一个线程提供下载,一个线程进行写入磁盘。两个线程尽量同时工作

假设所有数据块的大小固定,使用一个全局缓存区Block g_buffer[BUFFER_COUNT]

对应伪代码:

class Thread{public:Thread(void (*work_func)());~Thread();void start();void Abort();};class Semaphore{public:Semaphore(int count,int max_count);~Semaphore();void Unsignal();void Signal();};class Mutex{public:WaitMutex();RealeaseMutex();};#define BUFFER_COUNT 100Block g_buffer[BUFFER_COUNT]Thread g_threadA[ProcA];Thread g_threadB[ProcB];Semaphore g_seFull(0,BUFFER_COUNT);Semaphore g_seEmpty(BUFFER_COUNT,BUFFER_COUNT);bool g_downloadComplete;int in_index=0;int out_index=0;void main(){g_downloadComplete=false;threadA.start();threadB.start();}void ProcA(){while(true){g_seEmpty.Unsignal();g_downloadComplete=GetBloackFromNet(g_buffer+in_index);in_index=(in_index+1)%BUFFER_COUNT;g_seFull.Signal();if(g_downloadComplete)break;}}void ProcB(){while (true){g_seFull.Unsignal();WriteBlockToDisk(g_buffer+out_index);out_index=(out_index+1)%BUFFER_COUNT;g_seEmpty().Signal();if(g_downloadComplete && out_index==in_index)break;}}