Posted on 2010-04-01 09:17
kk 阅读(623)
评论(0) 编辑 收藏 引用 所属分类:
C++
环形缓冲是可以不用加锁的。下面是一个实现的环形缓冲。使用c实现,可能会出现write满情况,这种情况导致的结果就是write不成功,数据没写进去。
我这里只是简单的丢了。
1 //
2
3 #include "stdafx.h"
4 #include <windows.h>
5 #include <time.h>
6 #include <stdlib.h>
7
8 #define MAX_BUF_LEN 20 // buf len // 必须要大于1
9 int nRead = 0; // read pos
10 int nWrite = 0; // write pos
11 int buf[MAX_BUF_LEN] = {0}; // loop buf
12
13 #define NN 20000
14 __int64 sum = 0;
15 __int64 lose = 0;
16 __int64 total = (__int64)(1+NN)*(__int64)NN/2;
17 bool bWriteFinished = false;
18
19 void WriteBuf(int n)
20 {
21 int rpos = nRead;
22 int wpos = nWrite;
23 wpos++;
24 // buf满(即write又追上了read), 注为了避免与初始状态重复判断
25 // 所以这里最后一个buf没有写就认为已经满了。所以MAX_BUF_LEN不能为1
26 // 这里,直接丢弃该buf
27 if (wpos % MAX_BUF_LEN == rpos % MAX_BUF_LEN)
28 {
29 lose += n;
30 return;
31 }
32
33 buf[nWrite] = n;
34 nWrite++;
35 if (nWrite == MAX_BUF_LEN)
36 nWrite = 0;
37 }
38
39 int ReadBuf()
40 {
41 if (nWrite == nRead)
42 return -1;
43
44 int n = buf[nRead];
45 nRead++;
46 if (nRead == MAX_BUF_LEN)
47 nRead = 0;
48 return n;
49 }
50
51 DWORD WINAPI ReadThread(LPVOID lpParameter)
52 {
53 int tmp = 0;
54 int count = 0;
55 while (true)
56 {
57 //printf("ReadThread = %d\n", ReadBuf());
58 tmp = ReadBuf();
59 if (-1 != tmp)
60 {
61 count++;
62 sum += tmp;
63 if (count == NN)
64 {
65 printf ("ReadThread finished!\n");
66 break;
67 }
68 }
69 else if (bWriteFinished)
70 {
71 printf ("ReadThread finished222!\n");
72 break;
73 }
74
75 Sleep(rand() % 10);
76 }
77 return 0;
78 }
79
80 DWORD WINAPI WriteThread(LPVOID lpParameter)
81 {
82 int n = 0;
83 while (true)
84 {
85 n++;
86 WriteBuf(n);
87 if (n == NN)
88 {
89 printf ("WriteThread finished!\n");
90 bWriteFinished = true;
91 break;
92 }
93
94 Sleep(rand() % 10);
95 }
96 return 0;
97 }
98
99 int main(int argc, char* argv[])
100 {
101 srand(time(NULL));
102 // for (int i = 0; i < 10; i++)
103 // {
104 // printf ("rand = %d\n", rand() % 10);
105 // }
106
107 DWORD threadid[2] = {0};
108 HANDLE hThread[2] = {0};
109 int param = 0;
110 hThread[0] = CreateThread(NULL, 0, ReadThread, ¶m, CREATE_SUSPENDED, &threadid[0]);
111 ResumeThread(hThread[0]);
112 hThread[1] = CreateThread(NULL, 0, WriteThread, ¶m, CREATE_SUSPENDED, &threadid[1]);
113 ResumeThread(hThread[1]);
114
115 getchar();
116
117 printf ("total = %lld\n", total);
118 printf ("lose = %lld\n", lose);
119 printf ("sum = %lld\n", sum);
120
121 if (total == lose + sum)
122 {
123 printf ("loop buf works well!\n");
124 }
125 else
126 {
127 printf ("loop buf works wrong!\n");
128 }
129
130 return 0;
131 }
132
上面是加了测试代码的,我测试了一下似乎没问题。
注意:这里只允许一个线程读,一个线程写。如果是多个线程读写的话,需要锁!
另外,很多细节都没考虑进去