/********************
// Ƭ�� 1
// ����˵����һС�δ���������ǣ��������ݿɶ�������Ϳ��� recv ����
// ������ recv ����ʹ�� MSG_PEEK ����Ϊ���ã�Ӧ�������⡣
SOCKET sock;
char buff[256];
int done = 0, nBytes;
// ...
while (!done)
{
nBytes = recv(sock, buff, 65);
if (nBytes == SOCKET_ERROR)
{
printf("recv failed with error %d\n", WSAGetLastError());
Return;
}
DoComputationOnData(buff);
}
// ...
/********************/
//********************
// Ƭ�� 2
// ����δ��룬�����������ʣ�
// 1. �ڶ�ȡ�߳̽����ٽ����Ժ�ʹ���� recv �����Dz���һ���п��ܿ�������ô��
// 2. ���ٽ�������ִ��һ���������������������û�����⣿
// Ƭ�� 2 ͬƬ�� 1 ��ȣ���ʲô����֮���أ��ڶ�ȡ�߳�δ�����������ʱ�������ٽ�����Ĵ��ڣ�
// �����߳���������ݡ�
//
// Ƭ�� 2 ����ͼ�����Ƕ�ȡһ�κ�ȡ�̼߳����������ȡ��ͬʱ�����߳̿��Դ���ոն�ȡ
// ���Ƕ���ݡ��������Ƿ��ȡ�̵߳� SetEvent һ��ִ�У������߳̾�һ���ܸ��ڶ�ȡ�߳��ٴε�
// �� EnterCriticalSection ֮ǰ�ȵ��� EnterCriticalSection �أ�
// �Ҿ���һ����ȡ��һ��д�룬Ҳ���Բ�ʹ���ٽ����Ȼʹ���ٽ������������˳���£���ȡ��
// �̶�ȡ��ϣ�ִ�м����̣߳���Ƭ�� 2 �ź�Ƭ�� 1 ��Ч��һ��
#define MAX_BUFFER_SIZE 4096
// �ڴ��������߳�֮ǰ���ȳ�ʼ��һ���ٽ���data��������һ���Զ����õ��¼���hEvent��
CRITICAL_SECTION data;
HANDLE hEvent;
SOCKET sock;
TCHAR buff[MAX_BUFFER_SIZE];
int done = 0;
// ��������������
// ...
// ���ڶ�ȡ���߳�
void ReadThread(void)
{
int nTotal = 0,
nRead = 0,
nLeft = 0,
nBytes = 0;
while (!done)
{
nTotal = 0;
nLeft = NUM_BYTES_REQUIRED;
// �����ֽڹ����㹻�Ŀɴ�����ݣ����磬�������
while (nTotal != NUM_BYTES_REQUIRED)
{
EnterCriticalSection(&data);
nRead = recv(sock, &(buff[MAX_BUFFER_SIZE - nBytes]), nLeft, 0);
if (nRead == -1)
{
printf("error\n");
ExitThread();
}
nTotal += nRead;
nLeft -= nRead;
nBytes += nRead;
LeaveCriticalSection(&data);
}
SetEvent(hEvent);
}
}
// ���ڼ�����߳�
void ProcessThread(void)
{
WaitForSingleObject(hEvent);
EnterCriticalSection(&data);
DoSomeComputationOnData(buff);
// �Ѵ�������ݴ����뻺�������ߣ�Ȼ���ʣ�µ�����Ƶ�����Ŀ�ʼ��
nBytes -= NUM_BYTES_REQUIRED;
LeaveCriticalSection(&data);
}
/********************/