1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
#include <iostream>
#include <windows.h>
using namespace std;
#define maxthreads 4
DWORD id[maxthreads];
DWORD waiter;
HANDLE threadhandle[maxthreads];
DWORD WINAPI R1 (LPVOID);
DWORD WINAPI R2 (LPVOID);
DWORD WINAPI W1 (LPVOID);
DWORD WINAPI W2 (LPVOID);
int readcount=0,writecount=0,data,perform;
bool lock=false;
bool TestAndSet(bool *y)
{
bool rv=lock;
lock=true;
return rv;
}
DWORD WINAPI R1 (LPVOID)
{
while(TestAndSet(&lock))
while(lock==true);
readcount++;
cout << "R1 in CS." << endl;
cout << readcount << "Readers in CS." << endl;
cout << writecount << "Wrtiers in CS." << endl;
readcount--;
lock=false;
return (DWORD) 0;
}
DWORD WINAPI R2 (LPVOID)
{
while(TestAndSet(&lock))
while(lock==true);
readcount++;
cout << "R2 in CS." << endl;
cout << readcount << "Readers in CS." << endl;
cout << writecount << "Wrtiers in CS." << endl;
readcount--;
lock=false;
return (DWORD) 0;
}
DWORD WINAPI W1 (LPVOID)
{
while(TestAndSet(&lock))
while(lock==true);
writecount++;
cout << "W1 in CS." << endl;
cout << readcount << "Readers in CS." << endl;
cout << writecount << "Wrtiers in CS." << endl;
for (int s=0;s<=1000;s++)
{
perform*=s;
data +=perform;
}
writecount--;
lock=false;
return (DWORD) 0;
}
DWORD WINAPI W2 (LPVOID)
{
while(TestAndSet(&lock))
while(lock==true);
writecount++;
cout << "W2 in CS." << endl;
cout << readcount << "Readers in CS." << endl;
cout << writecount << "Wrtiers in CS." << endl;
for (int s=0;s<=1000;s++)
{
perform*=s;
data +=perform;
}
writecount--;
lock=false;
return (DWORD) 0;
}
int main(int argc, char *argv[])
{
threadhandle[0]=CreateThread(NULL,0,R1,(LPVOID)0,0,&id[0]);
threadhandle[1]=CreateThread(NULL,0,R2,(LPVOID)0,0,&id[1]);
threadhandle[2]=CreateThread(NULL,0,W1,(LPVOID)0,0,&id[2]);
threadhandle[3]=CreateThread(NULL,0,W2,(LPVOID)0,0,&id[3]);
waiter = WaitForMultipleObjects(maxthreads,threadhandle,TRUE,INFINITE);
for(int i = 0; i < maxthreads; i++)
{
CloseHandle(threadhandle[i]);
}
}
|