-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducer.cpp
More file actions
55 lines (48 loc) · 1.72 KB
/
producer.cpp
File metadata and controls
55 lines (48 loc) · 1.72 KB
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
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <iostream>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
int SMemory;
int* table;
// allocate shared memory
SMemory = shm_open("table", O_CREAT | O_RDWR, 0666); // create table which is a shared memory object
ftruncate(SMemory, sizeof(int));// set size of shared memory
table = static_cast<int*>(mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, SMemory, 0)); // maps shared memory to address
sem_t* full = sem_open("full", O_CREAT, 0666, 0); // creates semaphores
sem_t* empty = sem_open("empty", O_CREAT, 0666, 3);
sem_t* mutex = sem_open("mutex", O_CREAT, 0666, 1);
std::cout << "a processes is running...\n" << std::endl;
// loop through the operation 5 times
for (int i = 0; i < 5; ++i) {
sem_wait(empty);
sleep(1); // sleep for 1 sec
sem_wait(mutex); // unlock mutex
if (*table < 2) { // if the table does not have 2 items
++(*table); // add new item in the table
std::cout << "An item has been Produced: " << std::endl << "Table contains: " << *table << " items\n";
}
else {
std::cout << "Table is full!\n";
}
sem_post(mutex); // close the mutex
sem_post(full);
}
sleep(3); // sleep for 1 sec
std::cout << "Press enter to exit the completed process.";
// closes and unlinks the semaphores
sem_close(full);
sem_close(empty);
sem_close(mutex);
sem_unlink("full");
sem_unlink("empty");
sem_unlink("mutex");
// deallocates the shared memory
munmap(table, sizeof(int));
close(SMemory);
shm_unlink("table");
return 0;
}