// Ethernet.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Ethernet.h"
//#include "CSMA030390.h"
#include "cmath"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinThread *thread1,*thread2;//定义变量
DWORD ID1,ID2,Bus=0;//初始化共享内存
UINT aThread(LPVOID pParam);//线程A代表主机A
UINT bThread(LPVOID pParam);//线程B代表主机B
using namespace std;
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
//CString strHello;
//strHello.LoadString(IDS_HELLO);
//cout << (LPCTSTR)strHello << endl;
thread1=AfxBeginThread(aThread,NULL);//启动线程A
ID1=thread1->m_nThreadID;//线程A的ID号
thread2=AfxBeginThread(bThread,NULL);
ID2=thread2->m_nThreadID;
getchar();
}
return nRetCode;
}
UINT aThread(LPVOID pParam)
{
int i=0;
int CollisionCounter=16;//冲突次数
double collisionWindow=0.005;//冲突窗口取0.005
int randNum=rand()%3;//随机数
Loop:if(Bus==0)
{
Bus=Bus|ID1;//或符号
Sleep(12);
if(Bus==ID1)
{
printf("%d Send Success/n/n",ID1);
Bus=0;
CollisionCounter=16;
Sleep(rand()%10);
i++;
printf("主机A发送成功次数=%d/n/n",i);
if(i<10)
goto Loop;
}
else
{
printf("%d Send Collision/n/n",ID1);
Bus=0;
CollisionCounter--;
if(CollisionCounter>0)
{
Sleep(randNum*(int)pow(2,(CollisionCounter>10)?10:CollisionCounter)*collisionWindow);
goto Loop;
}
else
printf("%ld send Failure/n/n",ID1);
}
}
goto Loop;
return 0;
}
UINT bThread(LPVOID pParam)
{
int j=0;
int CollisionCounter=16;
double collisionWindow=0.005;
int randNum=rand()%3;
Loop:if(Bus==0)
{
Sleep(2);
Bus=Bus|ID2;
Sleep(3);
if(Bus==ID2)
{
printf("%d Send Success/n/n",ID2);
Bus=0;
CollisionCounter=16;
Sleep(rand()%10);
j++;
printf("主机B发送成功次数=%d/n/n",j);
if(j<10)
goto Loop;
}
else
{
printf("%d Send Collision/n/n",ID2);
Bus=0;
CollisionCounter--;
if(CollisionCounter>0)
{
Sleep(randNum*(int)pow(2,(CollisionCounter>10)?10:CollisionCounter)*collisionWindow);
goto Loop;
}
else
printf("%ld send Failure/n/n",ID2);
}
}
goto Loop;
return 0;
}