Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #define HAVE_STRUCT_TIMESPEC
- #pragma comment(lib, "pthreadVC2.lib")
- #include <pthread.h>
- #include <semaphore.h>
- #include<stdlib.h>
- #include <time.h>
- #include <stdbool.h>
- #include <Windows.h>
- #define vMax 50 // maximum visitor threads
- #define dMax 5 // maximum doctor threads
- #define roomMax 4 // maximum visitors in a room
- #define MAX 100
- #define pshared 0 // 0:threads 1+:process
- #define key 1 // 1+:unlocked 0:locked
- #define BUFFER_SIZE 5 // 50 visitors + 3 doctors
- int buffer[BUFFER_SIZE];
- pthread_t visitorQueue[vMax];
- pthread_t doctorQueue[dMax];
- int visitorCursor, doctorCursor = 0;
- int visitorCount, doctorCount = 0;
- int peopleInside = 0;
- sem_t s;
- int i, number = 0;
- bool isDisplay = false; // Check if the display thread is created
- // Critical section, a thread enters the room
- void* enterRoom() {
- // enter room
- // pause a random perid
- // exit room
- int wait = 42; // generateTime();
- srand(time(0));
- printf("Visitor %lu wishes to enter.\n", pthread_self());
- printf("Visitor %lu entered the patient's room, waited for 42 ms.\n", GetThreadId());
- Sleep(wait);
- printf("Visitor %lu exited the patient's room, stayed for %d ms.\n", GetThreadId(), wait);
- sem_post(&s);
- exit(0);
- }
- //void* display() {
- // printf("Display -> In the room: %d doctors [ %d ], and %d visitors [ %d, %d]\n");
- // return NULL;
- //}
- // Specifies the thread type
- void type(){
- sem_wait(&s);
- if (visitorCount < vMax) {
- visitorCount++;
- visitorQueue[visitorCursor] = pthread_self(); // Add the thread to the visitor queue;
- visitorCursor = ++visitorCursor % vMax; // Increment circular cursor
- enterRoom();
- }
- else if (doctorCount < dMax) { // < 4 or < 5 if there's a doctor in the room
- doctorCount++;
- doctorQueue[doctorCursor] = pthread_self(); // Add the thread to the visitor queue;
- doctorCursor = ++doctorCursor % dMax; // Increment circular cursor
- }
- }
- int main() {
- pthread_t TID[BUFFER_SIZE + 1]; // one for display
- sem_init(&s, pshared, key);
- //pthread_create(&TID[i], NULL, (void*)display, NULL); // create a display thread
- for (i = 0; i < BUFFER_SIZE + 1; i++) {
- // create thread
- pthread_create(&TID[i], NULL, (void*)type, NULL);
- }
- for (i = 0; i < +1; i++) {
- //printf("Contents of visitor queue: %lu\n", visitorQueue[i]);
- }
- for (i = 0; i < BUFFER_SIZE + 1; i++) {
- // join thread (wait)
- pthread_join(TID[i], NULL);
- }
- // destory thread
- pthread_exit(0);
- // destroy semaphore
- sem_destroy(&s);
- return 0;
- }
- //
- //
- //int generateNumber(int max){
- // int num = (rand() % (max) + 1);
- // return num;
- //}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement