Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* AP 18-apr-05 bakery.c */
- /* an implementation of critical */
- /* sections based on bakery algorithm */
- # include "bakery.h"
- # include <stdio.h>
- # include <conio.h>
- # include <windows.h>
- # define MAX_THREAD 1024
- MY_LPCRITICAL_SECTION *sec;
- int count=0;
- struct _crit_sec {
- volatile int choosing[MAX_THREAD];
- volatile int number[MAX_THREAD];
- };
- void My_InitializeCriticalSection( MY_LPCRITICAL_SECTION * sec ) {
- int i;
- *sec = (MY_LPCRITICAL_SECTION) malloc (sizeof(struct _crit_sec));
- for(i=0; i<MAX_THREAD; i++) {
- (*sec)->choosing[i] = 0;
- (*sec)->number[i] = 0;
- }
- }
- void My_DeleteCriticalSection( MY_LPCRITICAL_SECTION sec ) {
- if (sec) free( sec );
- }
- void My_EnterCriticalSection( int myId, MY_LPCRITICAL_SECTION sec ) {
- int max, j;
- sec->choosing[myId] = 1;
- max = 0;
- for (j=0; j<MAX_THREAD; j++) {
- if(max < sec->number[j]) max = sec->number[j];
- }
- sec->number[myId] = max + 1;
- sec->choosing[myId] = 0;
- for (j = 0; j < MAX_THREAD; j++) {
- while (sec->choosing[j]);
- while (sec->number[j] != 0 &&
- (sec->number[j] < sec->number[myId] ||
- (sec->number[j] == sec->number[myId] && j < myId)));
- }
- }
- void My_LeaveCriticalSection( int myId, MY_LPCRITICAL_SECTION sec ) {
- sec->number[myId] = 0;
- }
- DWORD WINAPI ThreadFunction(LPVOID n)
- {
- do{
- My_EnterCriticalSection((int)n, sec);//Xin vào vùng tranh chấp
- if((int)n==0)//kiểm tra: là thread thứ nhất?
- {
- count++;//nếu đúng thì tăng biến count
- Sleep(2000);
- }
- else
- {
- count--;//Nếu không phải thì giảm biến count
- Sleep(2000);
- }
- printf("%d\n",count);//Hiển thị biến count
- My_LeaveCriticalSection((int)n, sec);//Ra khỏi vùng tranh chấp
- }while(1);
- return 0;
- }
- void main(void)
- {
- HANDLE hThread[3];
- DWORD dwThreadID;
- int i;
- My_InitializeCriticalSection(&sec);//Khởi tạo vùng tranh chấp
- for(i=0;i<3;i++)
- {
- hThread[i]=CreateThread(NULL,0, ThreadFunction,(LPVOID)i,0, &dwThreadID);//Tạo Thread
- printf("Successful, ID=%d, hThread=%d\n", dwThreadID, hThread[i]);//Hiển thị thông tin Thread
- }
- Sleep(1000000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement