This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
headers.h
80 lines (72 loc) · 1.91 KB
/
headers.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/***** headers.h ******/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/time.h> // forgettimeofday()
// #include <semaphore.h>
#define SHM_KEY 12345
#define BUFFER_SIZE 2
#define PRODUCER_NUM 3
#define CONSUMER_NUM 1
#define COLOR_RED "RED"
#define COLOR_BLK "BLACK"
#define COLOR_WHITE "WHITE"
#define ITEM_NUM 1000
#define PRODUCER "PRODUCER"
#define CONSUMER "CONSUMER"
// item printed in buffer and producer and consumer files
typedef struct
{
char *color;
int timestamp;
} item;
// buffer with shared variable in for producer and out for consumer
typedef struct
{
// char *shm_pointer;
int in;
int out;
item buffer[BUFFER_SIZE];
int occupied_slots;
int available_slots;
int countdown;
int done;
int prod_state_ready;
int cons_state_ready;
} shared_struct;
// thread arguments
typedef struct
{
shared_struct *ptr; // shared by producer threads and consumer threads
FILE *fd; // file descriptor of output file
char *color;
} pthread_args;
// semaphore
typedef pthread_mutex_t mutex;
typedef pthread_cond_t cond;
typedef struct
{
int value; // value for semaphore
int counter; // # of pending signals
mutex *mutex; // lock and unlock, controls access to critical region
cond *cond; //
} semaphore;
// variables shared by all threads; mutable
static semaphore *sem;
// functions
item produce_item(char *color); // create a specific colored item and timestamp
void *producer(void *args); // producer thread
void *consumer(void *args); // consumer thread
semaphore *initialize_sem(int value);
void cond_wait(cond *cond, mutex *mutex);
void cond_signal(cond *cond);
void cond_broadcast(cond *cond);
void mutex_lock(mutex *mutex);
void mutex_unlock(mutex *mutex);
void sem_wait(semaphore *sem, shared_struct *ptr, char *client);
void sem_signal(semaphore *sem, shared_struct *ptr, char *client);