Search Results

Search found 69 results on 3 pages for 'semaphores'.

Page 1/3 | 1 2 3  | Next Page >

  • Operating systems theory -- using minimum number of semaphores

    - by stackuser
    This situation is prone to deadlock of processes in an operating system and I'd like to solve it with the minimum of semaphores. Basically there are three cooperating processes that all read data from the same input device. Each process, when it gets the input device, must read two consecutive data. I want to use mutual exclusion to do this. Semaphores should be used to synchronize: P1: P2: P3: input(a1,a2) input (b1,b2) input(c1,c2) Y=a1+c1 W=b2+c2 Z=a2+b1 Print (X) X=Z-Y+W The declaration and initialization that I think would work here are: semaphore s=1 sa1 = 0, sa2 = 0, sb1 = 0, sb2 = 0, sc1 = 0, sc2 = 0 I'm sure that any kernel programmers that happen on this can knock this out in a minute or 2. Diagram of cooperating Processes and one input device: It seems like P1 and P2 would start something like: wait(s) input (a1/b1, a2/b2) signal(s)

    Read the article

  • Operating systems -- using minimum number of semaphores

    - by stackuser
    The three cooperating processes all read data from the same input device. Each process, when it gets the input device, must read two consecutive data. I want to use mutual exclusion to do this. The declaration and initialization that I think would work here are: semaphore s=1 sa1 = 0, sa2 = 0, sb1 = 0, sb2 = 0, sc1 = 0, sc2 = 0 I'd like to use semaphores to synchronize the following processes: P1: P2: P3: input(a1,a2) input (b1,b2) input(c1,c2) Y=a1+c1 W=b2+c2 Z=a2+b1 Print (X) X=Z-Y+W I'm wondering how to use the minimum number of semaphores to solve this. Diagram of cooperating Processes and one input device: It seems like P1 and P2 would start something like: wait(s) input (a1/b1, a2/b2) signal(s)

    Read the article

  • Calculate travel time on road map with semaphores

    - by Ivansek
    I have a road map with intersections. At intersections there are semaphores. For each semaphore I generate a red light time and green light time which are represented with syntax [R:T1, G:T2], for example: 119 185 250 A ------- B: [R:6, G:4] ------ C: [R:5, G:5] ------ D I want to calculate a car travel time from A - D. Now I do this with this pseudo code: function get_travel_time(semaphores_configuration) { time = 0; for( i=1; i<path.length;i++) { prev_node = path[i-1]; next_node = path[i]); cost = cost_between(prev_node, next_node) time += (cost/movement_speed) // movement_speed = 50px per second light_times = get_light_times(path[i], semaphore_configurations) lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4] lights_sum = light_times.green_time+light_times.red_light; // Lights cycle time light = lights_cycle[cost%lights_sum]; if( light == "R" ) { time += light_times.red_light; } } return time; } So for distance 119 between A and B travel time is, 119/50 = 2.38s ( exactly mesaured time is between 2.5s and 2.6s), then we add time if we came at a red light when at B. If we came at a red light is calculated with lines: lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4] lights_sum = light_times.green_time+light_times.red_light light = lights_cycle[cost%lights_sum]; if( light == "R" ) { time += light_times.red_light; } This pseudo code doesn't calculate exactly the same times as they are mesaured, but the calculations are very close to them. Any idea how I would calculate this?

    Read the article

  • What are semaphores and how are they caused?

    - by tharkun
    I recently started having the problem that my Apache crashed and could not be restarted. The hosting company then told me that it has to do with 'semaphores' and sent me this snipped with which they solved the problem: /usr/bin/ipcrm sem $(/usr/bin/ipcs -s | grep www-data | awk '{print$2}') Now that's nice to have a command to execute that solves my problem but then again I have no clue what this is all about. What are semaphores and who the heck puts them, where they are and how do they crash my apache? I'd be really glad for some general explanations!

    Read the article

  • process semaphores linux - wait

    - by coubeatczech
    Hi, I try to code a simple program that starts and waits on the system semaphore until it gets terminated by signal. union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; int main(){ int semaphores = semget(IPC_PRIVATE,1,IPC_CREAT | 0666); union semun arg; arg.val = 0; semctl(semaphores,0,SETVAL,arg); struct sembuf operations[1]; operations[0].sem_num = 0; operations[0].sem_op = -1; operations[0].sem_flg = 0; semop(semaphores,operations,1); fprintf(stderr,"Why?\n"); return 0; } I expect, that everytime this program gets executed, nothing actually happens and it waits on the semaphore, but everytime it goes through the semaphore and writes Why?. Why?

    Read the article

  • Named semaphores in Python?

    - by Boaz
    Hi, I have a script in python which uses a resource which can not be used by more than a certain amount of concurrent scripts running. Classically, this would be solved by a named semaphores but I can not find those in the documentation of the multiprocessing module or threading . Am I missing something or are named semaphores not implemented / exposed by Python? and more importantly, if the answer is no, what is the best way to emulate one? Thanks, Boaz PS. For reasons which are not so relevant to this question, I can not aggregate the task to a continuously running process/daemon or work with spawned processed - both of which, it seems, would have worked with the python API.

    Read the article

  • Reading and writing to SysV shared memory without synchronization (use of semaphores, C/C++, Linux)

    - by user363778
    Hi, I use SysV shared memory to let two processes communicate with each other. I do not want the code to become to complex so I wondered if I really had to use semaphores to synchronize the access to the shared memory. In my C/C++ program the parent process reads from the shared memory and the child process writes to the shared memory. I wrote two test applications to see if I could produce some kind of error like a segmentation fault, but I couldn't (Ubuntu 10.04 64bit). Even two processes writing non stop in a while loop to the same shared memory did not produce any error. I hope someone has experience concerning this matter and can tell me if I really must use semaphores to synchronize the access or if I am OK without synchronization. Thanks

    Read the article

  • C semaphores: sem_wait throwing inexplicable error

    - by tocapa
    I'm working on a problem which we have to use semaphores to solve. I have an array which contains two semaphores, gsem, and given certain conditions call sem_wait(&(gsem[me])), which is supposed to waiting until that particular process is woken up. However, for some reason it gives me the error Bad file descriptor. I looked up sem_wait and the Open Group spec says this is not an error sem_wait can cause. This is making my whole program crazy and I have no idea why this is failing.

    Read the article

  • Semaphores in unmanaged code

    - by Dororo
    I've been using the Semaphore class to create semaphores. However, the examples use managed code (requires /clr), and I need to use unmanaged code because it seems FreeType doesn't like working with managed code. How can I create two simple threads which use a semaphore in unmanaged code?

    Read the article

  • Semaphores values

    - by Joel
    Hey, I have a question regarding using Semaphores HANDLE WINAPI CreateSemaphore(...); Is there anyway I can get the current value of the semaphore? Thanks, Joel

    Read the article

  • Creating semaphores with unmanaged code in C++

    - by Dororo
    I've been using the MSDN Library to create semaphores, located at: http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx However, the examples are using Managed code (requires /clr), and I need to use Unmanaged code because FreeType doesn't like working with Managed code it seems. How would I go about creating 2 simple threads which use a semaphore if I'm using unmanaged code? Many thanks for your help.

    Read the article

  • Can I implement the readers and writers algorithm in OpenMP by replacing counting semaphores with another feature?

    - by DeveloperDon
    After reading about OpenMP and not finding functions to support semaphores, I did an internet search for OpenMP and the readers and writers problem, but found no suitable matches. Is there a general method for replacing counting semaphores in OpenMP with something that it supports? Or is there just a gap in the environment where it does not permit things that are asymmetrical like the third readers and writers problem shown on the following page? http://en.wikipedia.org/wiki/Readers-writers_problem#The_third_readers-writers_problem

    Read the article

  • "The usage of semaphores is subtly wrong"

    - by Hoonose
    This past semester I was taking an OS practicum in C, in which the first project involved making a threads package, then writing a multiple producer-consumer program to demonstrate the functionality. However, after getting grading feedback, I lost points for "The usage of semaphores is subtly wrong" and "The program assumes preemption (e.g. uses yield to change control)" (We started with a non-preemptive threads package then added preemption later. Note that the comment and example contradict each other. I believe it doesn't assume either, and would work in both environments). This has been bugging me for a long time - the course staff was kind of overwhelmed, so I couldn't ask them what's wrong with this over the semester. I've spent a long time thinking about this and I can't see the issues. If anyone could take a look and point out the error, or reassure me that there actually isn't a problem, I'd really appreciate it. I believe the syntax should be pretty standard in terms of the thread package functions (minithreads and semaphores), but let me know if anything is confusing. #include <stdio.h> #include <stdlib.h> #include "minithread.h" #include "synch.h" #define BUFFER_SIZE 16 #define MAXCOUNT 100 int buffer[BUFFER_SIZE]; int size, head, tail; int count = 1; int out = 0; int toadd = 0; int toremove = 0; semaphore_t empty; semaphore_t full; semaphore_t count_lock; // Semaphore to keep a lock on the // global variables for maintaining the counts /* Method to handle the working of a student * The ID of a student is the corresponding minithread_id */ int student(int total_burgers) { int n, i; semaphore_P(count_lock); while ((out+toremove) < arg) { n = genintrand(BUFFER_SIZE); n = (n <= total_burgers - (out + toremove)) ? n : total_burgers - (out + toremove); printf("Student %d wants to get %d burgers ...\n", minithread_id(), n); toremove += n; semaphore_V(count_lock); for (i=0; i<n; i++) { semaphore_P(empty); out = buffer[tail]; printf("Student %d is taking burger %d.\n", minithread_id(), out); tail = (tail + 1) % BUFFER_SIZE; size--; toremove--; semaphore_V(full); } semaphore_P(count_lock); } semaphore_V(count_lock); printf("Student %d is done.\n", minithread_id()); return 0; } /* Method to handle the working of a cook * The ID of a cook is the corresponding minithread_id */ int cook(int total_burgers) { int n, i; printf("Creating Cook %d\n",minithread_id()); semaphore_P(count_lock); while ((count+toadd) <= arg) { n = genintrand(BUFFER_SIZE); n = (n <= total_burgers - (count + toadd) + 1) ? n : total_burgers - (count + toadd) + 1; printf("Cook %d wants to put %d burgers into the burger stack ...\n", minithread_id(),n); toadd += n; semaphore_V(count_lock); for (i=0; i<n; i++) { semaphore_P(full); printf("Cook %d is putting burger %d into the burger stack.\n", minithread_id(), count); buffer[head] = count++; head = (head + 1) % BUFFER_SIZE; size++; toadd--; semaphore_V(empty); } semaphore_P(count_lock); } semaphore_V(count_lock); printf("Cook %d is done.\n", minithread_id()); return 0; } /* Method to create our multiple producers and consumers * and start their respective threads by fork */ void starter(int* c){ int i; for (i=0;i<c[2];i++){ minithread_fork(cook, c[0]); } for (i=0;i<c[1];i++){ minithread_fork(student, c[0]); } } /* The arguments are passed as command line parameters * argv[1] is the no of students * argv[2] is the no of cooks */ void main(int argc, char *argv[]) { int pass_args[3]; pass_args[0] = MAXCOUNT; pass_args[1] = atoi(argv[1]); pass_args[2] = atoi(argv[2]); size = head = tail = 0; empty = semaphore_create(); semaphore_initialize(empty, 0); full = semaphore_create(); semaphore_initialize(full, BUFFER_SIZE); count_lock = semaphore_create(); semaphore_initialize(count_lock, 1); minithread_system_initialize(starter, pass_args); }

    Read the article

  • Limit Connections with semaphores

    - by Robert
    I'm trying to limit the number of connections my server will accept using semaphores, but when running, my code doesn't seem to make this restriction - am I using the semaphore correctly? eg. I have hardcoded the number of permit as 2, but I can connect an unlimited number of clients... public class EServer implements Runnable { private ServerSocket serverSocket; private int numberofConnections = 0; private Semaphore sem = new Semaphore(2); private volatile boolean keepProcessing = true; public EServer(int port) throws IOException { serverSocket = new ServerSocket(port); } @Override public void run() { while (keepProcessing) { try { sem.acquire(); Socket socket = serverSocket.accept(); process(socket, getNextConnectionNumber()); } catch (Exception e) { } finally { sem.release(); } } closeIgnoringException(serverSocket); } private synchronized int getNextConnectionNumber() { return ++numberofConnections; } // processing related methods }

    Read the article

  • How solve consumer/producer task using semaphores

    - by user1074896
    I have SimpleProducerConsumer class that illustrate consumer/producer problem (I am not sure that it's correct). public class SimpleProducerConsumer { private Stack<Object> stack = new Stack<Object>(); private static final int STACK_MAX_SIZE = 10; public static void main(String[] args) { SimpleProducerConsumer pc = new SimpleProducerConsumer(); new Thread(pc.new Producer(), "p1").start(); new Thread(pc.new Producer(), "p2").start(); new Thread(pc.new Consumer(), "c1").start(); new Thread(pc.new Consumer(), "c2").start(); new Thread(pc.new Consumer(), "c3").start(); } public synchronized void push(Object d) { while (stack.size() >= STACK_MAX_SIZE) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stack.push(new Object()); System.out.println("push " + Thread.currentThread().getName() + " " + stack.size()); notify(); } public synchronized Object pop() { while (stack.size() == 0) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } stack.pop(); System.out.println("pop " + Thread.currentThread().getName() + " " + stack.size()); notify(); return null; } class Consumer implements Runnable { @Override public void run() { while (true) { pop(); } } } class Producer implements Runnable { @Override public void run() { while (true) { push(new Object()); } } } } I found simple realization of semaphore(here:http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html I know that there is concurrency package) How I need to change code to exchange java objects monitors to my custom semaphore. (To illustrate C/P problem using semaphores) Semaphore: class Semaphore { private int counter; public Semaphore() { this(0); } public Semaphore(int i) { if (i < 0) throw new IllegalArgumentException(i + " < 0"); counter = i; } public synchronized void release() { if (counter == 0) { notify(); } counter++; } public synchronized void acquire() throws InterruptedException { while (counter == 0) { wait(); } counter--; } }

    Read the article

  • Locking semaphores in C problem sys/sem

    - by Vojtech R.
    Hi, I have problem with my functions. Sometimes two processes enter into critical section. I can't find problem in this after I spent 10 hours by debugging. On what I should aim? // lock semaphore static int P(int sem_id) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; /* P() */ sem_b.sem_flg = 0; if (semop(sem_id, &sem_b, 1) == -1) { print_error("semop in P", errno); return(0); } return(1); } // unlock semaphore static int V(int sem_id) { struct sembuf sem_b[1]; sem_b.sem_num = 0; sem_b.sem_op = 1; /* V() */ sem_b.sem_flg = 0; if (semop(sem_id, &sem_b, 1) == -1) { print_error("semop in V", errno); return(0); } return(1); } The action loop: int mutex; if ((mutex=semget(key, 1, 0666))>=0) { // semaphore exists } while(1) { P(mutex); assert(get_val(mutex)==0); (*action)++; V(mutex); } Many thanks

    Read the article

  • Where to start when programming process synchronization algorithms like clone/fork, semaphores

    - by David
    I am writing a program that simulates process synchronization. I am trying to implement the fork and semaphore techniques in C++, but am having trouble starting off. Do I just create a process and send it to fork from the very beginning? Is the program just going to be one infinite loop that goes back and forth between parent/child processes? And how do you create the idea of 'shared memory' in C++, explicit memory address or just some global variable? I just need to get the overall structure/idea of the flow of the program. Any references would be appreciated.

    Read the article

  • Java semaphore to syncronize printing to screen

    - by Travis Griswald
    I'm currently stuck on a bit of homework and was wondering if anyone could help - I have to use semaphores in java to syncronize printing letters from 2 threads - one printing "A" and one printing "B". I cannot print out more than 2 of the same character in a row, so output should look like AABABABABABBABABABABAABBAABBABABA At the moment I have 3 semaphores, a binary mutex set to 1, and a counting semaphore, and my thread classes look something like this - public void run() { while (true) { Time.delay(RandomGenerator.integer(0,20)); Semaphores.mutex.down (); System.out.println (produce()); if (printCount > 1) { printCount = 0; Semaphores.mutex.up (); Semaphores.printB.up(); } } } public String produce() { printCount++; return "A"; } public void run() { while (true) { Time.delay(RandomGenerator.integer(0,20)); Semaphores.mutex.down (); System.out.println (produce()); if (printCount > 1) { printCount = 0; Semaphores.mutex.up (); Semaphores.printA.up(); } } } public String produce() { printCount++; return "B"; } Yet whatever I try it either deadlocks, or it seems to be working only printing 2 in a row at most, but always seems to print 3 in a row every now and again! Any help is much appreciated, not looking code or anything just a few pointers if possible :)

    Read the article

  • Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?

    - by DeveloperDon
    In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements. The result was spaghetti code and the solution was structured programming. Similarly, pointers can have difficult to control characteristics in our programs. C++ started with plenty of pointers, but use of references are recommended. Libraries like STL can reduce some of our dependency. There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code. Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions). Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements. In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores. Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use? For example, a specific example of a system for multithread programming with multicore processors is OpenMP. It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment. th_id = omp_get_thread_num(); #pragma omp critical { cout << "Hello World from thread " << th_id << '\n'; } This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this: wait(sem); th_id = get_thread_num(); cout << "Hello World from thread " << th_id << '\n'; signal(sem); In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided. But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads. The consequences of creating deadlock or failing to make things thread safe can be hard to manage. Do these systems like OpenMP eliminate the problems with semaphores? Do they move the problem somewhere else? How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

    Read the article

  • Shared Memory and Process Sempahores (IPC)

    - by fsdfa
    This is an extract from Advanced Liniux Programming: Semaphores continue to exist even after all processes using them have terminated. The last process to use a semaphore set must explicitly remove it to ensure that the operating system does not run out of semaphores.To do so, invoke semctl with the semaphore identifier, the number of semaphores in the set, IPC_RMID as the third argument, and any union semun value as the fourth argument (which is ignored).The effective user ID of the calling process must match that of the semaphore’s allocator (or the caller must be root). Unlike shared memory segments, removing a semaphore set causes Linux to deallocate immediately. If a process allocate a shared memory, and many process use it and never set to delete it (with shmctl), if all them terminate, then the shared page continues being available. (We can see this with ipcs). If some process did the shmctl, then when the last process deattached, then the system will deallocate the shared memory. So far so good (I guess, if not, correct me). What I dont understand from that quote I did, is that first it say: "Semaphores continue to exist even after all processes using them have terminated." and then: "Unlike shared memory segments, removing a semaphore set causes Linux to deallocate immediately."

    Read the article

1 2 3  | Next Page >