Download presentation
Presentation is loading. Please wait.
1
Project 2 教學
2
Synchronization Functions in Windows HANDLE WINAPI CreateSemaphore ( __in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, __in LONG lInitialCount, __in LONG lMaximumCount, __in_opt LPCTSTR lpName); EX : The max value for the semaphore Sem is 5, and its initial value is 0 HANDLE Sem; Sem = CreateSemaphore( NULL,0,5,NULL);
3
Synchronization Functions in Windows DWORD WINAPI WaitForSingleObject ( __in HANDLE hHandle, __in DWORD dwMilliseconds); EX : to wait for a semaphore WaitForSingleObject( Sem, INFINITE );
4
Synchronization Functions in Windows BOOL WINAPI ReleaseSemaphore ( __in HANDLE hSemaphore, __in LONG lReleaseCount, __out_opt LPLONG lpPreviousCount); EX : to signal a sempahore ReleaseSemaphore(Sem, 1, NULL);
5
Synchronization Functions in Windows HANDLE WINAPI CreateThread ( __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in SIZE_T dwStackSize, __in LPTHREAD_START_ROUTINE lpStartAddress, __in_opt LPVOID lpParameter, __in DWORD dwCreationFlags, __out_opt LPDWORD lpThreadId); EX: to create a thread to execute function ABC CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ABC, NULL, 0,&ThreadID);
6
Synchronization Functions in Windows #include 可以使用 Dev-c 或 VC
7
EX:Hw2 in Windows int main(void) { full=CreateSemaphore( NULL,0,5,NULL); empty=CreateSemaphore( NULL,5,5,NULL); int j, *tid_arg; srand((int)time(0)); printf("start\n"); tid_arg = (int *) malloc(sizeof(int)); *tid_arg = 1; DWORD tid; Thread[0]=CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)producer, (void*)tid_arg, 0, &tid); Thread[1]=CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)consumer, (void*)tid_arg, 0, &tid); WaitForMultipleObjects(2, Thread, TRUE, INFINITE); system("pause"); return 0; }
8
EX:Hw2 in Windows void * producer(void *arg) { printf("p_in\n"); int i,tid,in_data; tid = *((int *) arg); free(arg); for (i=0;i<12;i++){ WaitForSingleObject( empty, INFINITE); Sleep(rand()%5); in_data=rand()%256; printf(">>p(%d) =(%d),buf[%d]\n", i, in_data,top); buf[top] = in_data; top=(top+1)%5; ReleaseSemaphore(full, 1, NULL); } return 0; }
9
EX:Hw2 in Windows void * consumer(void *arg) { printf("c_in\n"); int i,tid,out_data; tid = *((int *) arg); free(arg); for (i=0;i<12;i++){ WaitForSingleObject( full, INFINITE); Sleep(rand()%10); out_data=buf[down]; printf(">>c(%d) =(%d),buf[%d]\n", i, out_data,down); down=(down+1)%5; ReleaseSemaphore(empty, 1, NULL); } return 0; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.