Skip to content

Commit e7727a5

Browse files
committed
first commit
0 parents  commit e7727a5

File tree

4 files changed

+432
-0
lines changed

4 files changed

+432
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Simulation and Modeling in Python 3<br/>[![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)](https://www.python.org/) [![NumPy](https://img.shields.io/badge/numpy-%23013243.svg?style=for-the-badge&logo=numpy&logoColor=white)](https://pypi.org/project/numpy/) [![SciPy](https://img.shields.io/badge/SciPy-%230C55A5.svg?style=for-the-badge&logo=scipy&logoColor=%white)](https://pypi.org/project/scipy/) [![Matplotlib](https://img.shields.io/badge/Matplotlib-%23ffffff.svg?style=for-the-badge&logo=Matplotlib&logoColor=black)](https://pypi.org/project/matplotlib/) ![OpenCV](https://img.shields.io/badge/opencv-%23white.svg?style=for-the-badge&logo=opencv&logoColor=white) ![Jupyter Notebook](https://img.shields.io/badge/jupyter-%23FA0F00.svg?style=for-the-badge&logo=jupyter&logoColor=white) ![Visual Studio Code](https://img.shields.io/badge/Visual%20Studio%20Code-0078d7.svg?style=for-the-badge&logo=visual-studio-code&logoColor=white)
2+
3+
## Installations
4+
5+
* **Python 3** can be downloaded from [here](https://www.python.org/downloads/). Make sure to check **Add Python 3.x to PATH** during installation.
6+
* **NumPy**, **SciPy**, and **matplotlib** **etc** libraries can be downloaded and installed using the commands:
7+
```bash
8+
pip install numpy
9+
pip install scipy
10+
pip install matplotlib
11+
pip install library-name
12+
```
13+
or if you have multiple python version installed use this
14+
```bash
15+
py -3.9 -m pip install numpy
16+
py -3.11 -m pip install numpy
17+
.....
18+
```
19+
20+
## Code for Academic Course CIT-322 (Operating System Sessional)
21+
#### `**********************`
22+
<hr/>
23+
24+
### Lab - 1 == Peterson Solution (Producer Consumer Problem)
25+
[jupyter File](./peterson_solution.ipynb) <br/>
26+
[Python File](./same_python_file/peterson_solution.py) &nbsp;&nbsp; / &nbsp;&nbsp; [Python File Alternative](./same_python_file/peterson_solution_alternative.py)
27+
28+
### Lab - 2 == Poisson Distribution Example
29+
[jupyter File](./poisson_distribution.ipynb) <br/>
30+
[Python File](./same_python_file/poisson_distribution.py)
31+
32+
### Lab - 3 == Unimodal Multimodal Density Curves Normal Distribution Example
33+
[jupyter File](./unimodal_multimodal_density_curves_normal_distribution.ipynb) <br/>
34+
[Python File](./same_python_file/unimodal_multimodal_density_curves_normal_distribution.py)
35+
36+
### Lab - 4 == Exponential Distribution
37+
[jupyter File](./exponential_distribution.ipynb) <br/>
38+
[Python File](./same_python_file/exponential_distribution.py)
39+
40+
### Lab - 5 == Inverse Exponential Distribution Example (Random variates)
41+
[jupyter File](./inverse_exponential_distribution.ipynb) <br/>
42+
[Python File](./same_python_file/inverse_exponential_distribution.py)
43+
44+
45+
<hr/><hr/><hr/>
46+
47+
### 2.3 Numerical Integration using Monte Carlo Method
48+
[Jupyter File Alternative 2](./numerical_integration_using_monte_alternative_2.ipynb) &nbsp;&nbsp; / &nbsp;&nbsp; [Jupyter File Alternative 3](./numerical_integration_using_monte_alternative_3.ipynb) &nbsp;&nbsp; / &nbsp;&nbsp; [Jupyter File](./numerical_integration_using_monte.ipynb) <br/>
49+
[Python File Alternative 2](./same_python_file/numerical_integration_using_monte_alternative_2.py) &nbsp;&nbsp; / &nbsp;&nbsp; [Python File Alternative 3](./same_python_file/numerical_integration_using_monte_alternative_3.py)

peterson_solution.ipynb

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"Peterson's Solution is a classic algorithm used to solve the critical-section problem in concurrent programming. The critical-section problem arises when multiple processes or threads need to access a shared resource (such as shared memory or a shared data structure) concurrently. To prevent data inconsistency and ensure the correctness of the program, mutual exclusion must be enforced, meaning only one process can access the shared resource at a time.\n",
8+
"\n",
9+
"Peterson's Solution is based on the idea of using shared variables to coordinate the access to the critical section. It is primarily designed for systems with two processes that need to access a shared resource. The algorithm ensures that only one process is in its critical section at any given time, thus providing mutual exclusion.\n",
10+
"\n",
11+
"The algorithm relies on the following shared variables:\n",
12+
"\n",
13+
"- `int turn`: A variable that indicates whose turn it is to enter the critical section.\n",
14+
"- `bool flag[2]`: An array of flags that each process uses to indicate its intention to enter the critical section. `flag[i]` is true if process `i` wants to enter the critical section.\n",
15+
"\n",
16+
"The key idea of Peterson's Solution is that before entering the critical section, each process sets its `flag` to true and then sets `turn` to its own process number. Then it enters a loop where it checks if the other process also wants to enter the critical section. If the other process is in the critical section (indicated by its `flag` being true), and it has the turn (indicated by `turn` being equal to the other process number), the current process waits (spins) until it can enter the critical section. If not, it proceeds to enter its critical section.\n",
17+
"\n",
18+
"The pseudocode for Peterson's Solution is as follows:\n",
19+
"\n",
20+
"``` python\n",
21+
"# Shared variables\n",
22+
"int turn = 0\n",
23+
"bool flag[2] = {false, false}\n",
24+
"\n",
25+
"# Process 0\n",
26+
"flag[0] = true\n",
27+
"turn = 1\n",
28+
"while flag[1] and turn == 1:\n",
29+
" # Wait\n",
30+
"# Critical section\n",
31+
"# Exit section\n",
32+
"flag[0] = false\n",
33+
"\n",
34+
"# Process 1\n",
35+
"flag[1] = true\n",
36+
"turn = 0\n",
37+
"while flag[0] and turn == 0:\n",
38+
" # Wait\n",
39+
"# Critical section\n",
40+
"# Exit section\n",
41+
"flag[1] = false\n",
42+
"```\n",
43+
"\n",
44+
"The key property of Peterson's Solution is that it provides mutual exclusion, meaning only one process can be in its critical section at a time. Additionally, the algorithm guarantees progress, ensuring that a process that wants to enter the critical section will eventually do so as long as the other process does not remain indefinitely in its critical section.\n",
45+
"\n",
46+
"It's important to note that while Peterson's Solution is a simple and elegant algorithm, it is not suitable for scenarios with more than two processes."
47+
]
48+
},
49+
{
50+
"cell_type": "code",
51+
"execution_count": null,
52+
"metadata": {},
53+
"outputs": [],
54+
"source": [
55+
"import threading\n",
56+
"import time\n",
57+
"\n",
58+
"cs = 0\n",
59+
"flag_0 = False\n",
60+
"flag_1 = False\n",
61+
"turn = 0\n",
62+
"\n",
63+
"def thread_0():\n",
64+
" global cs, flag_0, flag_1, turn\n",
65+
"\n",
66+
" flag_0 = True\n",
67+
" turn = 1\n",
68+
" while (flag_1 and turn == 1):\n",
69+
" continue\n",
70+
"\n",
71+
" for i in range(10):\n",
72+
" cs += 1\n",
73+
" print(\"Thread 0: cs =\", cs)\n",
74+
" time.sleep(0.1)\n",
75+
"\n",
76+
" flag_0 = False\n",
77+
"\n",
78+
"def thread_1():\n",
79+
" global cs, flag_0, flag_1, turn\n",
80+
"\n",
81+
" flag_1 = True\n",
82+
" turn = 0\n",
83+
" while (flag_0 and turn == 0):\n",
84+
" continue\n",
85+
"\n",
86+
" for i in range(10):\n",
87+
" cs += 1000\n",
88+
" print(\"Thread 1: cs =\", cs)\n",
89+
" time.sleep(0.1)\n",
90+
"\n",
91+
" flag_1 = False\n",
92+
"\n",
93+
"if __name__ == \"__main__\":\n",
94+
"\t\tt0 = threading.Thread(target=thread_0)\n",
95+
"\t\tt1 = threading.Thread(target=thread_1)\n",
96+
"\t\tt0.start()\n",
97+
"\t\tt1.start()"
98+
]
99+
},
100+
{
101+
"cell_type": "markdown",
102+
"metadata": {},
103+
"source": [
104+
"### Alternative"
105+
]
106+
},
107+
{
108+
"cell_type": "code",
109+
"execution_count": null,
110+
"metadata": {},
111+
"outputs": [],
112+
"source": [
113+
"import threading\n",
114+
"import time\n",
115+
"\n",
116+
"# Shared variables\n",
117+
"turn = 0\n",
118+
"flag = [False, False]\n",
119+
"\n",
120+
"def process_0():\n",
121+
" global turn, flag\n",
122+
" flag[0] = True\n",
123+
" turn = 1\n",
124+
" while flag[1] and turn == 1:\n",
125+
" # Wait\n",
126+
" pass\n",
127+
" # Critical section\n",
128+
" print(\"Process 0 is in the critical section.\")\n",
129+
" time.sleep(2) # Simulating some work inside the critical section\n",
130+
" # Exit section\n",
131+
" flag[0] = False\n",
132+
" print(\"Process 0 exited the critical section.\\n\")\n",
133+
"\n",
134+
"def process_1():\n",
135+
" global turn, flag\n",
136+
" flag[1] = True\n",
137+
" turn = 0\n",
138+
" while flag[0] and turn == 0:\n",
139+
" # Wait\n",
140+
" pass\n",
141+
" # Critical section\n",
142+
" print(\"Process 1 is in the critical section.\")\n",
143+
" time.sleep(1) # Simulating some work inside the critical section\n",
144+
" # Exit section\n",
145+
" flag[1] = False\n",
146+
" print(\"Process 1 exited the critical section.\\n\")\n",
147+
"\n",
148+
"if __name__ == \"__main__\":\n",
149+
" thread_0 = threading.Thread(target=process_0)\n",
150+
" thread_1 = threading.Thread(target=process_1)\n",
151+
"\n",
152+
" thread_0.start()\n",
153+
" thread_1.start()\n",
154+
"\n",
155+
" thread_0.join()\n",
156+
" thread_1.join()\n",
157+
"\n",
158+
" print(\"Both processes have completed.\")\n"
159+
]
160+
},
161+
{
162+
"cell_type": "markdown",
163+
"metadata": {},
164+
"source": [
165+
"### Alternative"
166+
]
167+
},
168+
{
169+
"cell_type": "markdown",
170+
"metadata": {},
171+
"source": [
172+
"The producer-consumer problem (or bounded buffer problem) describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue. Producers produce an item and put it into the buffer. If the buffer is already full then the producer will have to wait for an empty block in the buffer. Consumers consume an item from the buffer. If the buffer is already empty then the consumer will have to wait for an item in the buffer. Implement Peterson’s Algorithm for the two processes using shared memory such that there is mutual exclusion between them. The solution should have free from synchronization problems. "
173+
]
174+
},
175+
{
176+
"cell_type": "code",
177+
"execution_count": null,
178+
"metadata": {},
179+
"outputs": [],
180+
"source": [
181+
"import random\n",
182+
"import time\n",
183+
"import threading\n",
184+
"import logging\n",
185+
"import queue\n",
186+
"\n",
187+
"BSIZE = 8 # Buffer size\n",
188+
"PWT = 2 # Producer wait time limit\n",
189+
"CWT = 10 # Consumer wait time limit\n",
190+
"RT = 10 # Program run-time in seconds\n",
191+
"\n",
192+
"def myrand(n):\n",
193+
" return random.randint(1, n)\n",
194+
"\n",
195+
"def producer(queue, state):\n",
196+
" index = 0\n",
197+
" while state:\n",
198+
" time.sleep(1)\n",
199+
" logging.info(\"\\nProducer is ready now.\")\n",
200+
" with queue.lock:\n",
201+
" if not queue.full():\n",
202+
" tempo = myrand(BSIZE * 3)\n",
203+
" logging.info(f\"Job {tempo} has been produced\")\n",
204+
" queue.put(tempo)\n",
205+
" logging.info(f\"Buffer: {list(queue.queue)}\")\n",
206+
" else:\n",
207+
" logging.info(\"Buffer is full, nothing can be produced!!!\")\n",
208+
" wait_time = myrand(PWT)\n",
209+
" logging.info(f\"Producer will wait for {wait_time} seconds\")\n",
210+
" time.sleep(wait_time)\n",
211+
"\n",
212+
"def consumer(queue, state):\n",
213+
" time.sleep(5)\n",
214+
" while state:\n",
215+
" time.sleep(1)\n",
216+
" logging.info(\"\\nConsumer is ready now.\")\n",
217+
" with queue.lock:\n",
218+
" if not queue.empty():\n",
219+
" job = queue.get()\n",
220+
" logging.info(f\"Job {job} has been consumed\")\n",
221+
" logging.info(f\"Buffer: {list(queue.queue)}\")\n",
222+
" else:\n",
223+
" logging.info(\"Buffer is empty, nothing can be consumed!!!\")\n",
224+
" wait_time = myrand(CWT)\n",
225+
" logging.info(f\"Consumer will sleep for {wait_time} seconds\")\n",
226+
" time.sleep(wait_time)\n",
227+
"\n",
228+
"if __name__ == \"__main__\":\n",
229+
" logging.basicConfig(level=logging.INFO, format='%(message)s')\n",
230+
"\n",
231+
" shared_queue = queue.Queue(BSIZE)\n",
232+
" shared_queue.lock = threading.Lock()\n",
233+
" state = True\n",
234+
"\n",
235+
" producer_thread = threading.Thread(target=producer, args=(shared_queue, state))\n",
236+
" consumer_thread = threading.Thread(target=consumer, args=(shared_queue, state))\n",
237+
"\n",
238+
" producer_thread.start()\n",
239+
" consumer_thread.start()\n",
240+
"\n",
241+
" time.sleep(RT)\n",
242+
" state = False\n",
243+
"\n",
244+
" producer_thread.join()\n",
245+
" consumer_thread.join()\n",
246+
"\n",
247+
" logging.info(\"\\nThe clock ran out.\")\n"
248+
]
249+
}
250+
],
251+
"metadata": {
252+
"kernelspec": {
253+
"display_name": "Python 3",
254+
"language": "python",
255+
"name": "python3"
256+
},
257+
"language_info": {
258+
"codemirror_mode": {
259+
"name": "ipython",
260+
"version": 3
261+
},
262+
"file_extension": ".py",
263+
"mimetype": "text/x-python",
264+
"name": "python",
265+
"nbconvert_exporter": "python",
266+
"pygments_lexer": "ipython3",
267+
"version": "3.11.0"
268+
},
269+
"orig_nbformat": 4
270+
},
271+
"nbformat": 4,
272+
"nbformat_minor": 2
273+
}

same_python_file/peterson_solution.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import threading
2+
import time
3+
4+
cs = 0
5+
flag_0 = False
6+
flag_1 = False
7+
turn = 0
8+
9+
def thread_0():
10+
global cs, flag_0, flag_1, turn
11+
12+
flag_0 = True
13+
turn = 1
14+
while (flag_1 and turn == 1):
15+
continue
16+
17+
for i in range(10):
18+
cs += 1
19+
print("Thread 0: cs =", cs)
20+
time.sleep(0.1)
21+
22+
flag_0 = False
23+
24+
def thread_1():
25+
global cs, flag_0, flag_1, turn
26+
27+
flag_1 = True
28+
turn = 0
29+
while (flag_0 and turn == 0):
30+
continue
31+
32+
for i in range(10):
33+
cs += 1000
34+
print("Thread 1: cs =", cs)
35+
time.sleep(0.1)
36+
37+
flag_1 = False
38+
39+
if __name__ == "__main__":
40+
t0 = threading.Thread(target=thread_0)
41+
t1 = threading.Thread(target=thread_1)
42+
t0.start()
43+
t1.start()

0 commit comments

Comments
 (0)