1 / 12

生產者與消費者的例子

生產者與消費者的例子. 使用共享記憶體機制 生產者及消費者的行程共享了下列的變數: #define BUF_SIZE n //n 是緩衝區的大小 int iIn = 0, iOut = 0 // iIn 表示緩衝區內 空 的位置, iOut 代表緩衝區內最先可用資料的位置 user_def_type buffer[BUF_SIZE] 這個例子中同時最多只能使用到 n-1 個緩衝區的空間. 生產者. do { … 產生一個型別為 user_def_type 的資料並存放於 nextp … /* 若緩衝區己滿則等待 * /

nelly
Download Presentation

生產者與消費者的例子

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 生產者與消費者的例子 • 使用共享記憶體機制 • 生產者及消費者的行程共享了下列的變數: • #define BUF_SIZE n //n是緩衝區的大小 • int iIn = 0, iOut = 0 //iIn表示緩衝區內空的位置,iOut代表緩衝區內最先可用資料的位置 • user_def_type buffer[BUF_SIZE] • 這個例子中同時最多只能使用到 n-1 個緩衝區的空間

  2. 生產者 do { … 產生一個型別為 user_def_type 的資料並存放於 nextp … /* 若緩衝區己滿則等待 */ while ((iIn + 1) % BUF_SIZE == iOut); ; buffer[iIn] = nextp; iIn = (iIn + 1) % BUF_SIZE; } while (FALSE);

  3. 消費者 do { while (iIn = iOut); /* 若緩衝區為空則等待 */ ; nextc = buffer[iOut]; iOut = (iOut + 1) % BUF_SIZE; … 將存於 nextc 的資料消耗掉 … } while (FALSE);

  4. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(緩衝區是空的) iOut iIn

  5. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(生產資料A) A iIn iOut

  6. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(生產資料B) iIn B A iOut

  7. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(生產資料C) iIn C B A iOut

  8. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(消費資料) iIn C B nextc A iOut

  9. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(消費資料) iIn C nextc B iOut

  10. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(生產資料D) D iOut C iIn

  11. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(生產資料E) D iOut C E iIn

  12. [3] [2] [4] [1] [0] 生產者-消費者運作示意圖(生產資料F) D iOut C E F iIn 緩衝區已滿!!

More Related