C++编程之美-代码清单1-17

代码清单1-17

#define BUFFER_COUNT 100
Block 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();
     // wait here till threads finished
}
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_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;
     } 
}
发布了1181 篇原创文章 · 获赞 951 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/104027253