数据结构太菜了
#define BUFFER_SIZE 10 /* the size of the buffer */
int count = 0; /* the number of data items in the buffer */
char buf[BUFFER_SIZE]; /* the buffer (circular buffer) */
int head = 0; /* index of the head data in the buffer */
int tail = 0; /* index of the tail data in the buffer */
HANDLE hMutexR, hMutexW;
DWORD thread_count = 1;
int arr[5];
DWORD WINAPI WriteProc( LPVOID lpParam )
{
while (1)
{
DWORD dwWaitResult = WaitForSingleObject(hMutexR, INFINITE);
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
{
__try
{
// Write
int tmp = tail;
tmp = (tmp +1)%BUFFER_SIZE;
if (tmp != head)
{
printf("Thread %d Write index %d/n", GetCurrentThreadId(), tail);
tail = (tail + 1)%BUFFER_SIZE;
}else{
printf("队列已满/n");
}
}
__finally
{
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutexR))
{
// Deal with error.
}
}
}
break;
// Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
printf("%d time out/n", GetCurrentThreadId());
break;
default:
break;
}
}
return 0;
}
DWORD WINAPI ReadProc( LPVOID lpParam )
{
while (1)
{
DWORD dwWaitResult = WaitForSingleObject(hMutexR, INFINITE);
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
{
__try {
// Read
if (head != tail)
{
printf("Thread %d Read index %d/n", GetCurrentThreadId(), head);
head = (head + 1)%BUFFER_SIZE;
Sleep(1000);
}else
{
printf("无内容可读取/n");
}
}
__finally
{
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutexR))
{
// Deal with error.
}
}
break;
}
// Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
printf("%d time out/n", GetCurrentThreadId());
break;
default:
break;
}
}
return 0;
}
void main(int argc, char* argv[])
{
DWORD ThreadID;
HANDLE hThreadRead[2];
HANDLE hThreadWrite[2];
hMutexR = CreateMutex(NULL, FALSE, NULL);
if (hMutexR == NULL)
{
printf("CreateMutex error/n");
}
hMutexW = CreateMutex(NULL, FALSE, NULL);
if (hMutexW == NULL)
{
printf("CreateMutex error/n");
}
for (int i = 0; i < thread_count ; i++)
{
hThreadRead[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) ReadProc,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
hThreadWrite[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) WriteProc,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
}
WaitForMultipleObjects(thread_count, hThreadRead, TRUE, INFINITE);
WaitForMultipleObjects(thread_count, hThreadWrite, TRUE, INFINITE);
system("pause");
}