-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducer.cpp
More file actions
55 lines (44 loc) · 1.46 KB
/
producer.cpp
File metadata and controls
55 lines (44 loc) · 1.46 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
#include <pthread.h>
#include <iostream>
#include "table_data.h"
/*
Nazeer Ahmad for OS.
I should've implemented shared memory in the header file then i
*/
using namespace std;
void *producer(void *nun) {
int item = 1;
for (int i = 0; i < MAX; i++) {
sem_wait(&table.empty); // Wait for an empty slot on the table
pthread_mutex_lock(&table.lock); // Acquire the lock to access the table
// Put the item on the table
for (int j = 0; j < SIZE_DATA; j++) {
if (table.items[j] == 0) {
table.items[j] = item; // add item to table
cout << "Produced item " << item << endl;
item++; // produce till 2
break;
}
}
// Release the lock and signal that a slot on the table is now full
pthread_mutex_unlock(&table.lock);
sem_post(&table.full);
}
pthread_exit(NULL);
}
int main() {
// Initialize the synchronization variables
sem_init(&table.empty, 0, SIZE_DATA);
sem_init(&table.full, 0, 0);
pthread_mutex_init(&table.lock, NULL);
// Create the producer and consumer threads
pthread_t prod_thd;
pthread_create(&prod_thd, NULL, producer, NULL);
// Wait for the threads to finish
pthread_join(prod_thd, NULL);
// Clean up the synchronization variables
sem_destroy(&table.empty);
sem_destroy(&table.full);
pthread_mutex_destroy(&table.lock);
return 0;
}