You are on page 1of 3

ng V Hi Long 10520386

Bi a: #include "windows.h" #include "stdio.h" #include "conio.h" static CRITICAL_SECTION sec; static LPCRITICAL_SECTION lpsec = &sec; static int count=0;

BO CO THC HNH HH BUI 3

DWORD WINAPI thread_proc (LPVOID para) { do { EnterCriticalSection(lpsec); if((int)para==0) { count+=1; printf("\n %d",count); printf(" added by thread 1..."); } else { count-=1; printf("\n %d",count); printf(" subed by thread %d...",(int)para+1); } LeaveCriticalSection( lpsec ); Sleep(2000); } while (1); } int main() { HANDLE thread[3]; int i; InitializeCriticalSection(lpsec); for (i=0;i<3;i++) { thread[i]=CreateThread(NULL,0,thread_proc,(LPVOID)i,0,NULL); if (thread[i]) printf("\nThread %d created successfully...",i); else { printf("\nFail %d...",i); return 1; } } Sleep(1000); getch(); return 0; }

Bi b: Code:
#include "stdafx.h" #include "conio.h" # include <stdio.h> # include <stdlib.h> # include <windows.h> static static static static HANDLE semaphore; int counter; int max_counter; int min_counter;

DWORD WINAPI Producer(LPVOID arg) { int iter = 0; do { WaitForSingleObject( semaphore, INFINITE ); counter++; if (counter > max_counter) max_counter = counter; printf("Producer: counter = %d\n", counter); ReleaseMutex( semaphore ); iter++; } while (iter < 1000); return 0;

DWORD WINAPI Consumer(LPVOID arg) { int iter = 0; int i; DWORD ret;

do {

ret = WaitForSingleObject( semaphore, INFINITE ); counter--; if( counter < min_counter) min_counter = counter; printf("Consumer: counter = %d\n", counter); iter++; ReleaseMutex( semaphore ); } while (iter < 1000); return 0;

void main () { HANDLE hProducer, hConsumer; HANDLE semaphore = CreateMutex( NULL, FALSE, NULL ); printf("GetCurrentProcessId = %d", GetCurrentProcessId()); hProducer = CreateThread( NULL, 0, Producer, NULL, 0, NULL ); hConsumer = CreateThread( NULL, 0, Consumer, NULL, 0, NULL ); WaitForSingleObject( hProducer, INFINITE ); WaitForSingleObject( hConsumer, INFINITE ); printf("%d <= counter <= %d\n", min_counter, max_counter); CloseHandle( semaphore ); getch(); }

You might also like