/* * Do Windows Viste nema potpunog ekvivalenta 'uvjetnim varijablama', * pa su one ovdje simulirane sa: * cond_signal(red, monitor) { * ReleaseMutex(monitor); * WaitForSingleObject(red, INFINITE); * WaitForSingleObject(monitor, INFINITE); * } * cond_signal(red) { SetEvent(red); } * uz stvaranje 'dogadjaja': * red = CreateEvent(NULL, FALSE, FALSE, NULL); * * Windows Vista i "Longhorn" imaju novi mehanizam: Condition Variables, * funkcije koje su gotovo identicne onima na UNIXu, sto se vidi iz iz opisa: * * Condition variable function - Description * ---------------------------------------------------------------------------- * InitializeConditionVariable - Initializes a condition variable. * SleepConditionVariableCS - Sleeps on the specified condition variable * and releases the specified critical section * as an atomic operation. * SleepConditionVariableSRW - Sleeps on the specified condition variable * and releases the specified SRW lock as an * atomic operation. * WakeAllConditionVariable - Wakes all threads waiting on the specified * condition variable. * WakeConditionVariable - Wakes a single thread waiting on the specified * condition variable. * */ #include #include #include #include HANDLE monitor; HANDLE red[5]; int filozof[5], vilica[5], kraj=0, jeo[5]={0,0,0,0,0}; void ispisi(int n){ printf("%c %c %c %c %c (%d)\t jeli: %d %d %d %d %d\n", filozof[0], filozof[1], filozof[2], filozof[3], filozof[4], n+1, jeo[0], jeo[1], jeo[2], jeo[3], jeo[4] ); } void misliti(){ Sleep(3000); } void jesti(n){ /* n - redni broj filozofa */ WaitForSingleObject(monitor, INFINITE); filozof[n]='o'; while (vilica[n]==0 || vilica[(n+1)%5]==0) { ReleaseMutex(monitor); WaitForSingleObject(red[n], INFINITE); WaitForSingleObject(monitor, INFINITE); } vilica[n]=vilica[(n+1)%5]=0; filozof[n]='X'; jeo[n]++; ispisi(n); ReleaseMutex(monitor); Sleep(2000); WaitForSingleObject(monitor, INFINITE); filozof[n]='O'; vilica[n]=vilica[(n+1)%5]=1; SetEvent(red[(n+4)%5]); SetEvent(red[(n+1)%5]); ispisi(n); ReleaseMutex(monitor); } DWORD WINAPI dretva(int n) { while(kraj!=1){ misliti(); jesti(n); } return 1; } int main(){ int i; HANDLE hThread[5]; DWORD dwThreadId; monitor = CreateMutex(NULL, FALSE, NULL); if (monitor == NULL) { printf("CreateMutex error: %d\n", GetLastError()); } for(i=0; i<5; i++){ filozof[i]='0'; vilica[i]=1; red[i]=CreateEvent(NULL, FALSE, FALSE, NULL); } for(i=0; i<5; i++){ hThread[i] = CreateThread(NULL, 0, dretva, i, 0, &dwThreadId); } for(i=0; i<5; i++){ WaitForSingleObject(hThread[i], INFINITE); } return 0; }