Premium Essay

Semaphores

In:

Submitted By oxkhan
Words 518
Pages 3
Header files
#include <sys/types.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#define SHM_KEY 123
#define SEM_KEY 456
#define PLAIN 0
#define CHOC 1 const int shared_segment_size = 0x6400; union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf;
};

Create sem
#include "my_ipc.h" int main( int argc, char *argv[])
{
int sem_id, proj_id; if ( (sem_id = semget (SEM_KEY, 2, IPC_CREAT | IPC_EXCL | 0600 )) == -1 ) {perror ("Unable to create semaphore"); exit(5); }printf ("sem_id is %d\n", sem_id ); semaphore_initialize (sem_id);
}int semaphore_initialize (int semid)
{ union semun argument; unsigned short values[2]; values[PLAIN] = 0; values[CHOC] = 0; argument.array = values; return semctl (semid, 0, SETALL, argument);
}

Producer_consumer
#include "my_ipc.h" int main()
{ int sem_id, user_type, plain, choc; char *shared_memory; if ( (sem_id = semget (SEM_KEY, 1, 0600 )) == -1 ) { perror ("Unable to get hold of the semaphore "); exit(5); } printf ("Enter 0 if you are a producer or 1 if you are a consumer : "); scanf ("%d", &user_type ); if ( user_type ) { printf ("How many plain doughnuts you want to consume : "); scanf ("%d", &plain ); printf ("How many chocolate doughnuts you want to consume : "); scanf ("%d", &choc ); semaphore_wait (sem_id, plain, choc); printf ("Process %d done eating doughnuts\n", getpid()); }else { printf ("How many plain doughnuts you want to produce : "); scanf ("%d", &plain ); printf ("How many chocolate doughnuts you want to produce : "); scanf

Similar Documents

Free Essay

Enron Book Cookers

...1746 about two hundred monks each held a twenty five foot wire and connected them. This connection of wires became a catalyst to what we now know as the internet. Inspired by the monk experiment which proved the power of electricity, many scientists there after tried their luck at creating an electric signaling system, and some succeeded at producing different designs of the telegraph. Through these different modifications of the telegraph we now have one of the most important innovations of this time the internet, whose roots can be argued to originate from the telegraph. Through the Victorian Internet one learns that one small idea can expand into a larger idea or a web of ideas. When one finally produces their idea they may be surprised to find that their original plans for the use of the product may change when it is put on the market. People can come up with the brightest ideas sometimes without trying, and a lot of times inventions are made as solutions to common problems. There are also innovations, which are not original inventions, but one person takes another’s invention and makes changes to it with the hopes of making it better. The experiment with the monks in Paris of 1746 proved that electricity could travel long distances in a short period of time. After these findings it became evident that a device that used electricity to send signals would be more efficient than their present system of transmitting signals. This was indeed the first step in creating the telegraph...

Words: 953 - Pages: 4

Free Essay

Aquaponics

...concepts of semaphores. Definition A semaphore is a protected variable whose value can be accessed and altered only by the operations P and V and initialization operation called 'Semaphoiinitislize'. Binary Semaphores can assume only the value 0 or the value 1 counting semaphores also called general semaphores can assume only nonnegative values.   The P (or wait or sleep or down) operation on semaphores S, written as P(S) or wait (S), operates as follows: P(S):   IF   S  >  0                  THEN  S :=  S - 1                  ELSE   (wait on S)   The V (or signal or wakeup or up) operation on semaphore S, written as V(S) or signal (S), operates as follows: V(S):   IF  (one or more process are waiting on S)                 THEN (let one of these processes proceed)                 ELSE   S := S +1   Operations P and V are done as single, indivisible, atomic action. It is guaranteed that once a semaphore operations has stared, no other process can access the semaphore until operation has completed. Mutual exclusion on the semaphore, S, is enforced within P(S) and V(S). If several processes attempt a P(S) simultaneously, only process will be allowed to proceed. The other processes will be kept waiting, but the implementation of P and V guarantees that processes will not suffer indefinite postponement. Semaphores solve the lost-wakeup problem. Producer-Consumer Problem Using Semaphores The Solution to producer-consumer problem uses three semaphores, namely, full...

Words: 371 - Pages: 2

Premium Essay

Nt1310 Unit 1 Reaction Paper

... /* the buffer */ int counter; /* buffer counter */ pthread_mutex_t mutex; /* the mutex exclusion lock */ sem_t full,empty; /* the empty, full semaphores */ pthread_t tid; /* define process thread id's */ pthread_attr_t attr; /* set the default process thread attributes */ /* insert item into the buffer */ int insert_item(buffer_item inData) { /* define the insert item method */ if(counter < BUFFER_SIZE) { /* if buffer is empty, insert the items into the buffer */ buffer[counter] = inData; counter++; /* increase...

Words: 532 - Pages: 3

Free Essay

Ccnet

...deterministic Critical regions • Mutual exclusion • The part of the program where the shared memory (or something else) is accessed is called a critical section • This is not enough (more rules): – Not two processes simultaneously in their critical regions – No assumptions may be made about speed and number of CPUs – No process running outside its critical region may block another process – No process should have to wait forever to enter its critical region OS 2007-08 6 OS 2007-08 5 1 Ideally A enters critical region A B blocked B enters critical region B attempts to enter critical region B leaves critical region A leaves critical region Many solutions… • Disabling interrupts • Locks • TSL instruction (hardware) • Semaphores • Mutexes • Monitors • Message passing •… 7 OS 2007-08 8 OS 2007-08 Disabling interrupts • Simplest solution • CPU switches from process to process only when an interrupt occurs (e.g. the clock interrupt) • This approach can be taken by the kernel • Should the OS trust the user in disabling/enabling interrupts? Too dangerous! OS 2007-08 9 Locks • A lock variable (alone it doesn’t work)...

Words: 812 - Pages: 4

Premium Essay

Resources

...Resource Allocation Graphs Roger Henriksson Department of Computer Science Lund University The possibility of deadlock is an undesired property (to say the least) of safety-critical real-time systems. Therefore, a method to verify that a system cannot deadlock, or to detect possible deadlock situations, is of tremendous value. One such method is resource allocation graphs. As stated in Operating System Concepts by Peterson and Silberschatz [PS85], the occurrence of deadlock requires among other things that hold-wait situations exist and a circular chain of such hold-waits must exist. A resource allocation graph attempts to graphically illustrate all the hold-wait situations in a system. In this graph it is possible to search for cases of circular hold-wait. In their book, Peterson and Silberschatz [PS85] (Section 8.2.2) introduce a method for drawing resource allocation graphs. However, in their version the resource allocation graph shows all the hold-wait-states that exist at any one given point in time. This is a good tool for illustrating a transient state in the system, but in order to use their version of the graphs for detecting any possible deadlock situation we would have to draw a graph for each and every possible combination of execution state for all threads in the system. Then, each and every one of these graphs would have to be analysed for cycles indicating circular wait. This is clearly unpractical. Instead, we modify the method of drawing resource...

Words: 1937 - Pages: 8

Free Essay

Review

...to the Dining Phils1 that’s simple and wrong: void philosopher() { while(1) { sleep(); get_left_fork(); get_right_fork(); eat(); put_left_fork(); put_right_fork(); } } If every philosopher picks up the left fork at the same time, noone gets to eat - ever. Some other suboptimal alternatives: • Pick up the left fork, if the right fork isn’t available for a given time, put the left fork down, wait and try again. (Big problem if all philosophers wait the same time - we get the same failure mode as before, but repeated.) Even if each philosopher waits a different random time, an unlucky philosopher may starve (in the literal or technical sense). Require all philosophers to acquire a binary semaphore before picking up any forks. This guarantees that no philosopher starves (assuming that the semaphore is fair) but limits parallelism dramatically. (FreeBSD has a similar problem with multiprocessor...

Words: 1511 - Pages: 7

Premium Essay

Nt1310 Unit 1 Research Paper

...CS554BH1 SUBJECT: OPERATING SYSTEMS ASSIGNMENT: HOME WORK ASSIGNMENT-2 Submitted by: MOHAN KUMAR RAJU BORUKATI mborukati@rivier.edu Q(1): Let S and Q be two semaphores initialized to 1. Can the code for processes P0 and P1 shown below cause a deadlock? Explain your answer. (Compare the code below to the example on page 217 of the textbook.) P0 P1...

Words: 1060 - Pages: 5

Premium Essay

Nt1330 Unit 1 Question Paper

...threadsused for applications that are frequently block. Q15: What is a thread library? Name two thread libraries? Thread library provides concurrent programming, it provides the control to execution the multiple threads parallel in the shared memory. Thread library is done by time sharing on a single processor. The thread library for unix is POSIX1003.1c and win32 for windows. Q16: What is a race condition? The race condition occurs when more than one threads access the shared memory elements and they try to change the data at the same time. The memory access without any priority scheme,lock or other control mechanism. Q17: what is a semaphore? The semaphore is used to avoid dead lock. Semaphores are two types binary semaphores counting semaphores. Binary semaphores uses two values 0 and 1 they are used to lock and unlock the resource. Counting semaphores are used to share more than one resources to the processes. Q18: What is a monitor? Monitoris a program that supports the concurrency controlled access to shareddata. Only one process can enter in to the monitor and it can use the resources, after the exiting the process another process enters in to the monitor. Monitor features Providethe access control over shared data.Synchronizes is donebetween parallel executingthreads. Data is only accessed within the monitor. Monitoruses the system runtime calls that is EnterMonitor(),ExitMonitor(),Wait(),Signal(). 19: what is the critical-session problem? While we performing multi process/tasks...

Words: 1498 - Pages: 6

Free Essay

Srs Woow

...بسم الله الرحمن الرحيم Name: -------------------------------- Group:---- Level:------- Major:------------- |المملكة العربية السعودية |[pic] |KINGDOM OF SAUDI ARABIA | |وزارة التعليم العالي | |Ministry of Higher Education | |جامعة الإمام محمد بن سعود الإسلامية | |Al-Imam Muhammad Ibn Saud Islamic University | |كلية علوم الحاسب والمعلومات | |College of Computer & Information Sciences | CS231: Operating Systems 1st Mid-Term Exam 2nd semester of 1430/1431 Exam Duration: 1:30H Marks: out of 20 I. Multiple choices [6 Marks, 1 for each]: 1. Which of the following is not shared by different threads of the same process? a. Global variables b. Program counter c. Open files d. None of the above 2. Which of the following process state transitions is NOT correct? a. RUNNIG to READY b. READY to RUNNIG c. WAITING to RUNNING d. WAITING to READY 3. Which of the following programming examples, multithreading provides better performance than a single-threaded solution? a. A web server that responds clients service requests b. A web browser that can process...

Words: 693 - Pages: 3

Premium Essay

Client Server

...CLIENT SERVER PROGRAMMING AND MULTIMEDIA Introduction Client/server describes the relationship between two computer programs in which one program, the client, makes a service request from another program, the server, which fulfills the request. Although the client/server idea can be used by programs within a single computer, it is a more important idea in a network. In a network, the client/server model provides a convenient way to interconnect programs that are distributed efficiently across different locations. Computer transactions using the client/server model are very common. For example, to check your bank account from your computer, a client program in your computer forwards your request to a server program at the bank. That program may in turn forward the request to its own client program that sends a request to a database server at another bank computer to retrieve your account balance. The balance is returned back to the bank data client, which in turn serves it back to the client in your personal computer, which displays the information for you. The client/server model has become one of the central ideas of network computing. Most business applications being written today use the client/server model. So does the Internet's main program, TCP/IP. In marketing, the term has been used to distinguish distributed computing by smaller dispersed computers from the "monolithic" centralized computing of mainframe computers. But this distinction has largely disappeared...

Words: 2053 - Pages: 9

Free Essay

The Evolution of Telecommunications

...this spans across approximately 200 years and has gone through leap years of innovations. The pre-historic age brought about using the smoke from fire to send signals to others from miles away. In the Ancient Greek book, The Iliad by Homer, smoke fires were mentioned in those pages which were dated to have been written about the early 1200s B.C. Later, approximately 700 B.C., carrier pigeons were trained to take a message from one person to another by memorized route. This was a tactic that became popularized especially during the Olympic Games of Athens, Greece, and later in wars with the Persians and the Mongolians. In the late 1700s, the French-born Chappe brothers invented the Semaphore system, which consisted of movable arms on a pole that denoted letters; the first commercial semaphore was invented about 1794 and spread from Paris to Russian, Italy, and Germany; these towers only lasted until about 1860. In 1843, Alexander Bain invented the first FAX, which was followed closely by the electric Telegraph which was invented by Samuel Morse in 1844. The “Morse Code” was widely used to send distress signals especially during times of war or maritime disaster. It wasn’t until 1876 that Alexander Graham Bell invented the first Telephone and applies for a patent. However, Elisha Gray, founder of Western Electric Manufacturing, applies for the same patent a mere 3 hours after Bell does. Bell offers his patent for $100,000, and Gray refuses. 1877 sees the first telephone...

Words: 679 - Pages: 3

Free Essay

Os Study Guide

...COMP3361 Operating Systems I Mid-­term Review and Study Guide Basic Concepts: What is an operating system? A program that acts as an intermediary between a user of a computer and the computer hardware - basic functions? 1.) OS is a resource allocator 2.) manages all resources 3.) decides between conflicting requests for efficient and fair resource use 4.) OS is a control program 5.) controls execution of programs to prevent errors and improper use of the computer 6.) a program running at all times on the computer, usually called the kernel 7.)everything else is either a a.) system program: associated with the OS but not part of the kernel b.) application program: not associated with the OS user/kernel modes of operation? 1.) The operating system must ensure correct operation of the computer system. To prevent user programs from interfering with the proper operation of the system, the hardware has two modes: user mode and kernel mode. Various instructions (such as I/0 instructions and halt instructions) are privileged and can be executed only in kernel mode. 2.) Kernel Mode In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC. 3.) User Mode In User mode...

Words: 2427 - Pages: 10

Premium Essay

Development

...I. Network engineer interview questions OSPF A. Describe OSPF in your own words. B. OSPF areas, the purpose of having each of them C. Types of OSPF LSA, the purpose of each LSA type D. What exact LSA type you can see in different areas E. How OSPF establishes neighboor relation, what the stages are F. If OSPF router is stucked in each stage what the problem is and how to troubleshoot it G. OSPF hierarchy in the single or multi areas. Cool OSPF behavior in broadcast and non broadcast H. Draw the diagram of typical OSPF network and explain generally how it works, DR, BDR, election, ASBR, ABR, route redistribution and summarization STP A. How it works and the purpose B. Diff types (SSTP, MSTP, RSTP) Cisco - PVST/PVST+ C. root election D. Diff. port stages and timing for convergence E. Draw the typical diagram and explain how diff types of STP work F. What ports are blocking or forwarding G. How it works if there are topology changes ACLs A. What are they B. Diff types C. Write an example if you want to allow and to deny… D. Well-known port numbers (DNS - 53 and etc…) QOS A. What is that B. What is the diff b/w L2 and L3 QoS C. How it works Network: A. Draw the typical network diagram you have to deal with B. explain how it works C. What part of it you are responsible D. firewall, what is that, how it works, how it is diff from ACLs E. What problems with the network you had had and how you solved it. F. What...

Words: 2138 - Pages: 9

Free Essay

Test

...Contents At a Glance I Advanced UNIX Programming with Linux Advanced Linux Programming 1 Getting Started 3 2 Writing Good GNU/Linux Software 17 3 Processes 45 4 Threads 61 5 Interprocess Communication 95 II Mastering Linux 6 Devices 129 7 The /proc File System 147 8 Linux System Calls 167 9 Inline Assembly Code 189 10 Security 197 11 A Sample GNU/Linux Application 219 III Appendixes A Other Development Tools 259 B Low-Level I/O 281 C Table of Signals 301 D Online Resources 303 E Open Publication License Version 1.0 305 F GNU General Public License 309 Advanced Linux Programming Mark Mitchell, Jeffrey Oldham, and Alex Samuel www.newriders.com 201 West 103rd Street, Indianapolis, Indiana 46290 An Imprint of Pearson Education Boston • Indianapolis • London • Munich • New York • San Francisco Advanced Linux Programming Copyright © 2001 by New Riders Publishing FIRST EDITION: June, 2001 All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written permission from the publisher, except for the inclusion of brief quotations in a review. International Standard Book Number: 0-7357-1043-0 Library of Congress Catalog Card Number: 00-105343 05 04 03 02 01 7 6 5 4 3 2 1 Interpretation of the printing code:The rightmost doubledigit number is the year of the book’s printing; the rightmost single-digit...

Words: 80064 - Pages: 321

Free Essay

Gghj

...VIVA ZAPATA! MEXICAN CANTINA 6 SEMAPHORE ROAD, SEMAPHORE 5019 PH: 08 8242 2525 DINE IN MENU BOTANAS (APPETIZERS) Dips(to share) - all served with crunchy tortilla chips. Guacamole A creamy blend of ripe avocados, onions and our special sauce. $10.90 Tomato Con Chilli Cold and spicy tomato, onion and chilli dip. Frijole Con Queso A flavourful blend of beans, cheese and spices. Chilli Con Queso A tasty blend of cheese, hot chillies and spices. Combination Dips A platter of all 4 dips for those who cannot make up their minds. $10.60 $10.60 $10.60 S$18.90 L$26.90 NACHOS Nachos S$13.90L$18.90 Crispy hot tortilla chips smothered with melted cheese and crowned with jalepeno peppers. Baby Nachos Supreme For those who don't want to share. $14.90 Special Nachos S$19.90 L$26.90 Nachos as above with a delicious topping of guacamole, tomato con chilli and sour cream. Nachos Supreme As above on a bed of frijoles. S$20.50 L$28.90 ENTREMESES (ENTREES) Chicken Flautas $10.80 Two flour tortillas fried to crispy perfection with a delightfully seasoned filling of chicken topped with guacamole and salsa. Ribs Zapata $15.90 Pork spare ribs, basted with a spicy marinade, barbecued and smothered in our special sauce. Chilli Con Carne $13.90 A rich stew made from beans, ground beef, tomatoes, chilli and spices, served with crunchy corn chips. Prawn Taquitos $13.90 Two fingers of succulent prawn cutlets rolled in corn tortillas fried to crispy perfection. Guacamole and...

Words: 892 - Pages: 4