-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevel_3_Task 2_Multithreaded Application.cpp
More file actions
90 lines (70 loc) · 2.32 KB
/
Level_3_Task 2_Multithreaded Application.cpp
File metadata and controls
90 lines (70 loc) · 2.32 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
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
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <pthread.h> // i) POSIX thread
#include <unistd.h> // for sleep()
#define BUFFER_SIZE 5
using namespace std;
// ---------- Multithreaded Application producer-consumer using POSIX Thread -----------------
int buffer[BUFFER_SIZE];
int in = 0, out = 0, count = 0;
// ii) Implement synchronization using mutexes and condition variables
// Synchronization objects
pthread_mutex_t mutex;
pthread_cond_t notFull;
pthread_cond_t notEmpty;
// Producer thread function
void* producer (void* arg) {
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock (&mutex);
// Wait if buffer is full
while (count == BUFFER_SIZE) {
pthread_cond_wait (¬Full, &mutex);
}
buffer[in] = i;
cout << "Produced: " << buffer[in] << endl;
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal (¬Empty);
pthread_mutex_unlock (&mutex);
sleep(1);
}
return nullptr;
}
// Consumer thread function
void* consumer (void* arg) {
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock (&mutex);
// Wait if buffer is empty
while (count == 0) {
pthread_cond_wait (¬Empty, &mutex);
}
int item = buffer[out];
cout << "Consumed: " << item << endl;
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal (¬Full);
pthread_mutex_unlock (&mutex);
sleep(1);
}
return nullptr;
}
int main () {
cout << "-------------------------------------------------------\n";
cout << "\t Multithreaded Application using POSIX Thread\n";
cout << "-------------------------------------------------------\n";
pthread_t prodThread, consThread;
// Initialize mutex and condition variables
pthread_mutex_init (&mutex, nullptr);
pthread_cond_init (¬Full, nullptr);
pthread_cond_init (¬Empty, nullptr);
// Create threads
pthread_create (&prodThread, nullptr, producer, nullptr);
pthread_create (&consThread, nullptr, consumer, nullptr);
// Wait for threads to finish
pthread_join (prodThread, nullptr);
pthread_join (consThread, nullptr);
// Destroy synchronization objects
pthread_mutex_destroy (&mutex);
pthread_cond_destroy (¬Full);
pthread_cond_destroy (¬Empty);
return 0;
}