Old Producer/Consumer Example question

how would I take this code, the old producer/consumer example, and make it for 2 consumers and 1 producer?
basically, like this:
Producer put 1
Consumer #1 got 1
Consumer #2 got 1
Producer put 2
Consumer #1 got 2
Consumer #2 got 2
etc.....
***********Producer.java***************
public class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number
+ " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
***********Consumer.java***********
public class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number
+ " got: " + value);
***********CubbyHole.java***********
public class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) { }
available = false;
notifyAll();
return contents;
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
contents = value;
available = true;
notifyAll();
***********ProducerConsumerTest.java***********
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();

instantiate another consumer.
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
Consumer c2 = new Consumer(c, 2);
p1.start();
c1.start();
c2.start();
but then modify CubbyHole so that it checks that it has been consumed twice (as thats what you want, you said). Instead of using boolean available, use an integer flag that counts how many times its been consumed, and then reset the flag when it gets to 2. Something like that. Is this a college question? Do your homework. ha ha.

Similar Messages

  • Still stuck with the same old producer consumer weight problem need help

    Hello All,
    This is the problem I am stuck with right now.
    I have two array lists one producer array list and one consumer array list denoted by a and b
    P1 P2 P3 P4 P5
    5 6 7 8 9
    C1 C2 C3 C4 C5
    2 3 4 5 6
    Now we find all those producer consumer pairs which satisfy the criteria Pi>=Ci
    We have the following sets
    (5,2)(6,2)(7,2),(8,2),(9,2)
    (5,3)(6,3)(7,3),(8,3),(9,3)
    (5,4)(6,4)(7,4),(8,4),(9,4)
    (5,5)(6,5)(7,5),(8,5),(9,5)
    (6,6)(7,6)(8,6),(9,6)
    Let us done each of them with Si
    so we have S1,S2,S3,S4,S5
    we assign a third parameter called weight to each element in Si which has satisfied the condition Pi>=Ci;
    so we we will have
    (5,2,ai),(6,2,bi),(7,2,ci)....etc for S1
    similarly for S2 and so on.
    We need to find in each set Si the the pair which has the smallest weight.
    if we have (5,2,3) and (6,2,4) then 5,2,3 should be chosen.We should make sure that there is only one pair in every set which is finally chosen on the basis of weight.
    Suppose we get a pair (5,2,3) in S1 and (5,2,3) in S2 we should see that (5,2,3) is not used to compare to compare with any other elements in the same set S2,
    Finally we should arrive at the best element pair in each set.They should be non repeating in other sets.
    Given a problem
    P0 P1 P2 P3 P4
    9 5 2 2 8
    6 5 4 5 3
    C0 C1 C2 C3 C4
    we have So as (P0,C0) and (P4,C0)
    assuming that the one with the smaller index has lesser weight PO is selected.In the program I have used random weights.from set S1 we select the pair PO,CO
    S1 =(P0,C1),(P1,C1) and (P4,C1)
    since P0 and P4 are already used in previous set we dont use them for checking in S1 so we have (P1,C1) as best.
    S2=(P0,C2),(P1,C2) and (P4,C2) so we dont use P0,C2 and P1 and C2 because PO and P1 are already used in S1.
    So we choose P4,C2
    in S3 and S4 ae have (P0,C3),(P1,C3),(P4,C3) so we dont choose anything
    and same in S4 also.
    So answer is
    (P0,C0),(P1,C1) and (P4,C2).
    My program is trying to assign weights and I am trying to print the weights along with the sets.It doesnt work fine.I need help to write this program to do this.
    Thanks.
    Regards.
    NP
    What I have tried till now.
    I have one more question could you help me with this.
    I have an array list of this form.
    package mypackage1;
    import java.util.*;
    public class DD
    private  int P;
    private  int C;
    private int weight;
    public void set_p(int P1)
    P=P1;
    public void set_c(int C1)
    C=C1;
    public void set_weight(int W1)
    weight=W1;
    public int get_p()
    return P;
    public int get_c()
    return C;
    public int get_x()
    return weight;
    public static void main(String args[])
    ArrayList a=new ArrayList();
    ArrayList min_weights_int=new ArrayList();
    ArrayList rows=new ArrayList();
    ArrayList temp=new ArrayList();
    Hashtable h=new Hashtable();
    String v;
    int o=0;
    DD[] d=new DD[5];
    for(int i=0;i<4;i++)
    d=new DD();
    for(int i=0;i<4;i++)
    d[i].set_p(((int)(StrictMath.random()*10 + 1)));
    d[i].set_c((int)(StrictMath.random()*10 + 1));
    d[i].set_weight(0);
    System.out.println("Producers");
    for(int i=0;i<4;i++)
    System.out.println(d[i].get_p());
    System.out.println("Consumers");
    for(int i=0;i<4;i++)
    System.out.println(d[i].get_c());
    System.out.println("Weights");
    for(int i=0;i<4;i++)
    System.out.println(d[i].get_x());
    for(int i=0;i<4;i++ )
    int bi =d[i].get_c();
    ArrayList row=new ArrayList();
    for(int j=0;j<4;j++)
    if( d[j].get_p() >=bi)
    d[j].set_weight((int)(StrictMath.random()*10 + 1));
    row.add("(" + bi + "," + d[j].get_p() + "," +d[j].get_x() + ")");
    else
    d[j].set_weight(0);
    row.add("null");
    rows.add(row);
    System.out.println(rows);
    int f=0;
    for(Iterator p=rows.iterator();p.hasNext();)
    temp=(ArrayList)p.next();
    String S="S" +f;
    h.put(S,temp);
    String tt=new String();
    for(int j=0;j<4;j++)
    if(temp.get(j).toString() !="null")
    // System.out.println("In if loop");
    //System.out.println(temp.get(j).toString());
    String l=temp.get(j).toString();
    System.out.println(l);
    //System.out.println("Comma matches" + l.lastIndexOf(","));
    //System.out.println(min_weights);
    f++;
    for(Enumeration e=h.keys();e.hasMoreElements();)
    //System.out.println("I am here");
    int ii=0;
    int smallest=0;
    String key=(String)e.nextElement();
    System.out.println("key=" + key);
    temp=(ArrayList)h.get(key);
    System.out.println("Array List" + temp);
    for( int j=0;j<4;j++)
    String l=(temp.get(j).toString());
    if(l!="null")
    System.out.println("l=" +l);
    [\code]

    In your example you selected the pair with the greatest
    distance from the first set, and the pair with the least
    distance from the second. I don't see how the distance
    function was used.
    Also it's not clear to me that there is always a solution,
    and, if there is, whether consistently choosing the
    furthest or the closest pairs will always work.
    The most obvious approach is to systematically try
    all possibilities until the answer is reached, or there
    are no possibilities left. This means backtracking whenever
    a point is reached where you cannot continue. In this case
    backtrack one step and try another possibility at this
    step. After all possible choices of the previous step,
    backtrack one more step and so on.
    This seems rather involved, and it probably is.
    Interestingly, if you know Prolog, it is ridiculously
    easy because Prolog does all the backtracking for you.
    In Java, you can implement the algorithm in much the same
    way as Prolog implementations do it--keep a list of all the
    choice points and work through them until success or there
    are none left.
    If you do know Prolog, you could generate lots of random
    problems and see if there is always a solution.

  • Producer-Consumer example: why is this wrong?

    Hi,
    i wrote the following, which i know, that it is wrong. However, i cannot explain why.
    public class Buffer
        private int num;   
        //state: true-isFull, false-isEmpty;
        private boolean state;
        public Buffer()
            this.state=false;
        public synchronized boolean getState()
            return this.state;
        public synchronized int remove()
            this.state=false;
            return this.num;       
        public synchronized void add(int i)
            this.state=true;
            this.num=i;
    public class Producer implements Runnable
        Buffer b;
        public Producer(Buffer b)
            this.b=b;
        public void run()
            int i=0;
            while (b.getState())
                try
                    wait();
                catch(InterruptedException e)
            System.err.println("Producer now adding number..."+i);
            b.add(i++);
            notifyAll();       
    public class Consumer implements Runnable
        Buffer b;
        public Consumer(Buffer b)
            this.b=b;
        public void run()
            while (!b.getState())
                try
                    wait();
                catch(InterruptedException e)
            System.err.println("Consumer removed number..."+ b.remove());
            notifyAll();
    }init:
    deps-jar:
    compile-single:
    run-single:
    Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:474)
    at produceerconsumer.Consumer.run(Consumer.java:19)
    at java.lang.Thread.run(Thread.java:595)
    Producer now adding number...0
    Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at produceerconsumer.Producer.run(Producer.java:32)
    at java.lang.Thread.run(Thread.java:595)
    BUILD SUCCESSFUL (total time: 0 seconds)

    you can't call wait or notify unless you are synchronizing on the object you are waiting or notifying on.

  • Thread producer/multiple consumer example!!

    Hi,
    does anybody have an example of a procucer/multiple consumers thread
    example.
    I would like to do the following:
    -start one producer thread that writes data into an object.
    -start more consumer threads that read and process that data
    from that object.
    Conditions:
    -data put on the object should only be handled by one consumer!!
    (so if the data would be numbers: 1, 2, 3 than number 1 should
    be fetched by one consumer and the other consumers don't see it
    anymore!).
    If anybody has an example for this, please let me know!
    Thanks,
    Sven

    Check out Doug Lea's work
    http://g.cs.oswego.edu
    and the book
    http://java.sun.com/docs/books/cp/
    util.concurrent is a great package. It is utilized by many many big java projects. There is a producer consumer example in the book, using util.concurrent classes.
    -Spinoza

  • Producer Consumer (Semaphore?)

    I am trying to understand concurrency in Java and have tried to code a producer consumer example:
    package de.fasel;
    public class PackagingUnit {
         private int numberOfUnits;
         private static final int PACKAGE_SIZE = 50;
         public PackagingUnit() {
              this.numberOfUnits = 0;
         public void addUnit() {
                   numberOfUnits++;
                   notify();
         public void getPackage() {
              while (this.numberOfUnits < 50)
                   try {
                        wait();
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              this.numberOfUnits -= PACKAGE_SIZE;
    package de.fasel;
    import java.util.concurrent.TimeUnit;
    public class Producer implements Runnable {
         private int productionTime;
         private PackagingUnit pUnit;
         private String name;
          * @param productionTime in sec int
          * @param pUnit
          * @param name
         public Producer(int productionTime, PackagingUnit pUnit, String name) {
              this.productionTime = productionTime;
              this.pUnit = pUnit;
              this.name = name;
         public void run() {
              while (true) {
                   try {
                        TimeUnit.SECONDS.sleep(productionTime);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   this.pUnit.addUnit();
                   System.out.printf("%s has produced one unit", name);
    package de.fasel;
    public class Shipper implements Runnable {
         private PackagingUnit pUnit;
         public Shipper(PackagingUnit unit) {
              super();
              // TODO Auto-generated constructor stub
              pUnit = unit;
         public void run() {
              while(true) {
                   this.pUnit.getPackage();
                   System.out.println("One package has been shipped");
    package de.fasel;
    public class Tester {
         public static void main(String[] args) {
              PackagingUnit pUnit = new PackagingUnit();
              Producer p1 = new Producer(3, pUnit, "p1");
              Producer p2 = new Producer(2, pUnit, "p2");
              Producer p3 = new Producer(1, pUnit, "p3");
              Producer p4 = new Producer(1, pUnit, "p4");
              Shipper s = new Shipper(pUnit);
              Thread tp1 = new Thread(p1);
              tp1.start();
              Thread tp2 = new Thread(p2);
              tp2.start();
              Thread tp3 = new Thread(p3);
              tp3.start();
              Thread tp4 = new Thread(p4);
              tp4.start();
              Thread ts = new Thread(s);
              ts.start();
    }When I run this I get the following exception
    Exception in thread "Thread-4" java.lang.IllegalMonitorStateException: current thread not owner
         at java.lang.Object.wait(Native Method)
         at java.lang.Object.wait(Unknown Source)
         at de.fasel.PackagingUnit.getPackage(PackagingUnit.java:20)
         at de.fasel.Shipper.run(Shipper.java:15)
         at java.lang.Thread.run(Unknown Source)
    How can I make this work?
    Thanks

    Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor. Sorry that's a bit abstract, I am just trying to learn this stuff. I thought that was supposed to happen: One or several threads waiting for a resource until it becomes available. Why is this exception thrown?
    The PackagingUnit is designed analogous to the semaphore pattern from an IBM tutorial (Axel Roetter: Writing multithreaded Java applications). Unfortunately it does not show how to use (perhaps it is to obvious to most people).

  • Producer Consumer Query.

    I am Testing a small example of the Producer Consumer example
    using synchronized.
    I have a very important query which I need to ask:
    class Q has 2 synchronized methods,one to get() and one to put().
    class Producer and Consumer both have a reference to this object.
    Now look at the main() class ProducerConsumer,which instantiates Q
    and passes this reference to the Producer and Consumer.
    The Producer object then calls the put() method which is defined
    in a continous loop.This means that now the Q object has a lock
    by the Producer object.
    In that case,how can the Consumer object call the get() method.
    The Q object is locked by the Producer isnt it? (as the producer
    has invoked the put() and this is in a continous loop).
    The output shud be:
    Put 1
    Put 2
    Put n
    but the output I am getting is:
    Put 1
    Get 1
    Put 2
    Get 2
    How can this be possible?
    How can the Comsumer call get(),if the Producer has locked the object
    and has not released it as the synchronized put() is in a continous loop
    Has any one understood my query?
    class Q{
         private int n;
         public synchronized int get(){
              System.out.println("Got " + n);
              return n;
         public synchronized void put(int n){
              this.n = n;
              System.out.println("Put " + n);
    class Producer implements Runnable{
         Q q;
         Producer(Q q){
              this.q = q;
              new Thread(this,"Producer").start();
         public void run(){
              int i=0;
              while(true){
              q.put(i++);
    } // End of Producer.
    class Consumer implements Runnable{
         Q q;
         Consumer(Q q){
              this.q = q;
              new Thread(this,"Consumer").start();
         public void run(){
              int i=0;
              while(true){
              q.get();
    } // End of Producer.
    public class ProducerConsumer {
         public static void main(String[] args) {
          // Instantiate the Q.
          Q q = new Q();
          Producer producer = new Producer(q);
          Consumer consumer = new Consumer(q);
    }

    I am Testing a small example of the Producer Consumer example
    using synchronized.
    I have a very important query which I need to ask:
    class Q has 2 synchronized methods,one to get() and one to put().
    class Producer and Consumer both have a reference to this object.
    Now look at the main() class ProducerConsumer,which instantiates Q
    and passes this reference to the Producer and Consumer.
    The Producer object then calls the put() method which is defined
    in a continous loop.This means that now the Q object has a lock
    by the Producer object.
    In that case,how can the Consumer object call the get() method.
    The Q object is locked by the Producer isnt it? (as the producer
    has invoked the put() and this is in a continous loop).
    The output shud be:
    Put 1
    Put 2
    Put n
    but the output I am getting is:
    Put 1
    Get 1
    Put 2
    Get 2
    How can this be possible?
    How can the Comsumer call get(),if the Producer has locked the object
    and has not released it as the synchronized put() is in a continous loop
    Has any one understood my query?
    class Q{
         private int n;
         public synchronized int get(){
              System.out.println("Got " + n);
              return n;
         public synchronized void put(int n){
              this.n = n;
              System.out.println("Put " + n);
    class Producer implements Runnable{
         Q q;
         Producer(Q q){
              this.q = q;
              new Thread(this,"Producer").start();
         public void run(){
              int i=0;
              while(true){
              q.put(i++);
    } // End of Producer.
    class Consumer implements Runnable{
         Q q;
         Consumer(Q q){
              this.q = q;
              new Thread(this,"Consumer").start();
         public void run(){
              int i=0;
              while(true){
              q.get();
    } // End of Producer.
    public class ProducerConsumer {
         public static void main(String[] args) {
          // Instantiate the Q.
          Q q = new Q();
          Producer producer = new Producer(q);
          Consumer consumer = new Consumer(q);
    }

  • Classic Producer/Consumer question

    All,
    I've a straightforward (hopefully) question regarding the producer consumer thread example. While I get the entire picture - I have a question about the lines in the code :
                   sleep((int)(Math.random() 100));*
    in the Producer. WITHOUT this line, the output goes haywire (with Producer and Consumers putting/getting values randomly)- while with it, the producers and consumers start behaving normally (ie Producer Puts and Consumer Gets like clockwork)
    Why is it necessary to put this line in? What's it trying to put to sleep anyways and for what reason?
    public class DerTest {
         public static void main(String...argv) throws Exception {
              Holder holder = new Holder();
              Producer producer = new Producer(holder);
              Consumer consumer = new Consumer(holder);
              producer.start();
              consumer.start();
    class Holder {
         private int i;
         private boolean hasPut;
         public synchronized void put(int i) throws Exception {
              while(this.hasPut == true) {
                   wait();
              this.i = i;
              this.hasPut = true;
              notifyAll();
         public synchronized int get() throws Exception {
              while(this.hasPut == false) {
                   wait();
              this.hasPut = false;
              notifyAll();
              return this.i;
    class Producer extends Thread {
         private Holder holder;
         public Producer(Holder holder) {
              this.holder = holder;
         public void run() {
              int i = 0;
              try {
                   while(true) {
                        this.holder.put(i);
                        System.out.println("Putting : "+i);
                        i++;
                        sleep((int)(Math.random() * 100));
              } catch(Exception e) {
                   e.printStackTrace();
    class Consumer extends Thread {
         private Holder holder;
         public Consumer(Holder holder) {
              this.holder = holder;
         public void run() {
              try {
                   while(true) {
                        int i = this.holder.get();
                        System.out.println("Getting : "+i);
              } catch(Exception e) {
                   e.printStackTrace();
    }

    because the printlns are not synchronized with the get/put calls. put those printlns inside of the get/put methods and you will see the output you expect.

  • Producer/consumer question

    Hi everyone
    I am stucked with a problem using the producer/consumer VI.
    My VI continuously acquires data from the DAQ using a producer/consumer VI.
    In the maintime, I would like to introduce and save some notes that can help me to identify the acquired data in a separate file without stopping the acquisition.... but  I don't know how to do it or modify the producer/consumer scheme.
    Any suggestion?
    Thanks for the reply
    matomato
    Solved!
    Go to Solution.
    Attachments:
    ProducerConsumerData_time_Y_Sim_Start_13.vi ‏70 KB

    matomato wrote:
    Hi Smercurio_fc
    The purpose of the code with the Write to Spreadsheet File on the left is to save some comments without stopping the acquisition.
    The problem with it is that it only runs once at the beginning of the program.
    ...The new one should be be to introduce and save his details without stopping the acquisition.
    Save where? In this secondary file, or in the measurement file as a comment?
    Technically, I don't know how to modify the producer/consumer scheme to introduce the new loop with the case structure maintaining the data acquisition as the main loop.
    Hope to have answered your question, if not let me know.
    I'm not sure I understand what you are asking. Are you saying you don't know how to add another loop to the code? Or are you saying you don't know how to use the event structure?

  • How to change the transmissi​on rate of data flow in producer/ consumer pattern

    Hi All
    I am new to labview and trying to design a application to transfer image data in different rates, that means I can change the transfer rate in the transmission process. In fact,I refer to the the Queue Basic.vi to achieve this function by Changing the delay value of dequeue and enqueue.The program is divided into three parts:
    The first part is the sender in vc used to split and send image data.Data size is 226kb and each time we send a 1kb packet;
    The second is labview rate-change part,use producer/ consumer pattern and queue to transfer data;
    The third one is the receiver in vc,receive data in sequence and synthetic images.
    The entire transfer process is: image data was sent from the sender to producer loop through DLL, then enqueue--dequeue in consumer loop--DLL--receiver.The sleep time in vc sender is equal to the delay value in producer loop and this makes it look like the data generated as in the loop.
    Now this is where my dilemma is:
    When transferring data, if the producer loop and consumer loop delay value are equal(both 20ms), I can see image synthesis at a constant speed and no data lose; if I change the consumer loop delay value and make it greater than the producer delay(one is still 20ms and another is 50ms),that means receive in a lower rate and store data in queue. I can see Elements in Queue
    increase but the image data randomly lost, and the image synthesis speed is not reduced.
    My question is why image data loss and I can't see the image synthesis speed reduced when change the delay value in consumer loop?
    Do anyone know how to solve the problem? Are there any examples I can refer to? Any suggestions are greatly appreciated!
    Attachments:
    image1.JPG ‏56 KB

    thisoldman,
    I don't have '/usr/lib/modules/3.17.3-1-ARCH/build/Documentation/VGA-softcursor.txt' on my file system. Does it contain the info about changing the blinking speed?
    P.S. The other two links I found yet before starting this thread. I only found in them the recommendations about changing "the color and shape of the cursor and turning blinking on/off" (as I mentioned in the original question). Did I miss the info about the blinking speed?
    PPS: I found the vga-softcursor.txt here: https://www.kernel.org/doc/Documentatio … cursor.txt
    But that file doesn't tell about changing the blink rate either.
    Last edited by nbd (2014-11-23 20:55:41)

  • Input and output on same device, producer/consumer structure

    Hello interested people,
    I have a question about using the same device for both digital inputs
    and outputs.  I have written a simple program of one while loop
    that continuously polls the device, processes, and requests.  I
    have addressed the device using two DAQmx Asst. and I have attached
    them with their error in/out cluster terminals to provide data flow and
    eliminate the chance of addressing the devices at the same time (which
    produces an error).  Now I want to change this program structure
    to a producer/consumer loop foundation with state machine.  
    In this design, I will have the DI in the producer loop and the DO in
    the consumer loop, under one of the states.  I can't simply
    connect the error in/out ports in this configuration, so my question is
    how to avoid the error caused by addressing the same device
    simultaneously with two different tasks (input and output)?  I
    have attached two VI's, the "One Loop" vi is the original configuration
    (simplified), and the Producer-Consumer vi is a NONSENSICAL program
    that simply represents the desired configuration.  (I don't need
    any comments on the programming of this vi, it is only an example for
    illustration of the problem). 
    I am thinking about bundling the input data and the error cluster, both
    from the PXI 6528 DI, into one cluster, queueing that up, and
    unbundling the de-queued elements for some kind of data flow between
    the producer loop and the "Request" state of the consumer loop. 
    Is this the right approach, or am I barking up the wrong tree?
    Thanks
    Attachments:
    One Loop DO DI.vi ‏102 KB
    Producer-Consumer DI-DO.vi ‏106 KB

    Hello,
    It sounds to me like you really have two modes:
    1. user interface actions determine execution
    2. user interface is locked, and execution is automated.
    I think it would make sense to use the producer consumer for an architecture.  Basically you would do the following:
    1. program the producer to handle the user interface as you normally would.
    2. provide one additional event case in the producer which would be your "automated handling" case.  In that case, you could put a state machine which could run until whatever conditions were met to put your program back in "user interface mode".
    Keep in mind that you can use custom USER EVENTS to programmatically generate events ie. you can trigger the start of your "automated handling" form anywhere in your code at virtually any time.
    I think this would allow you to take advantage of the producer consumer architecture in its intended spirit, while integrating an automated routine.
    I hope this helps!
    Best Regards,
    JLS
    Best,
    JLS
    Sixclear

  • Producer consumer vs state machine

    Hi there,
    I have been on and around for quite a while to understand how can I re-design an application, which was originally built using a mix of sequence structure, while loops and event structures. And now I am making a newer version of the same application, for research purposes, while learning the LabVIEW techniques. Earlier I used LabVIEW versions 5 and 6 to make simple programs for fuzzy logic and neural networks. And that's not a good reference.
    Ok, after learning that Producer Consumer (PC) and Standard State Machines (SSM or SM) are two new approaches for a better (scalable, flexible and efficient) coding as suggest by veterans, in one thread where I asked about another issue, I have started digging into this topic and now I am on a point where I have to implement it finally (spent pretty much time in the learning phase).
    I have several questions.
    To start the discussion, I would give a brief description of my application.
    It's a networked application, where the network communication happens using DataSocket (one reason to use LabVIEW as the environment).
    We are talking about the client application, which communicates with other applications on remote computer, via Internet.
    User interface involves a tab control, with several pages-
    On startup, the controls/indicators (now onwards referred as controls only), are initialized, datasocket connection is checked (rather internet is checked, and a connection established with the remote datasocket server) (page 1)
    If connected to the datasocket server, the user selects Login/Registration (page 2)
    Login and/or Registration happen on page 3/4
    Then the user sees a table of remote users to connect to (page 5)
    Upon selection of a remote user, and after clicking on "connect", the user will see a video indicator, with a lot of other controls. (page 6)
    On this page with video indicator and controls, the user has a lot of activities, in which many messages are sent and received to/from the remote machine.
    the user may disconnect and go back to page 5, and log out and go back to page 2 and so on.
    I hope this is clear.
    I have thought about two different ways to do this application. Using PS or by SSM.
    In the attachments, I have given a diagram (with errors, of course, because of unlinked controls), for each of the approach, plus the original application's diagram.
    I hope this is sufficient for anybody to understand my case and give suggestions.
    I am looking for suggestions about which is a better model for my type of case. I have been to discussions like this one and saw that there are many issues regarding dequeue in PC model. So I am curious to know if SSM is a better and latest model or it's more primitive? Which looks better for my application's performance?
    Thanks ahead!
    Vaibhav
    Attachments:
    OldDesign.vi ‏41 KB
    PCDesign.vi ‏42 KB
    SSMDesign.vi ‏46 KB

    Vaibhav wrote:
    @ Harold
    Thanks. Any suggestion how can I start and stop that loop in parallel with other loops? Like, if some event occurs, the loop should start execution, and keep on moving, while other events are being traced and executed.
    In those examples where you had a while loop inside a case structure, that bit of code will only execute one time.  It will immediately read the boolean at the start of the program, if the value was true before the porgram started, then the while loop will run.  Once that while loop stops, the case structure will end.  It will never execute again unless you completely stop and restart your program.  If the boolean is false before the program starts, the false case will execute immediately.  Nothing happens since it is empty and it is done, never to run again (unless you stop and restart your VI)  You should turn the structure around.  Put the case structure in the while loop.  Make sure you put a small wait statement in the loop so that it doesn't run full speed eating up CPU cycles just polling the status of the boolean.
    @ Ravens
    Thanks for the detailed comment.
    One thing I would clarify. The user will not be able to switch between the pages using the tab control. The program will direct appropriate page to the user. I kept the tabs visible just for your idea of the pages. Sorry, I didn't mention that.
    Do you think it's still a bad design?
    If the tabs will be hidden or disabled, you will probably be okay.  I wouldn't call it a bad design.  I wouldn't do it that way.  But as long as you understand the possibility of problems and prevent that.  Especially some time down the road when you modify the program in some other way that could lead to a problem because you forgot about the dependencies of the event structures on the state of the state machine. 
    Yes, I agree about only one event structure to handle all the events. But since the user will not be able to click somewhere else, other than those possible controls, I thought to keep it like this.
    I thought the events are captured only if we are in that case. I think I am wrong, right? Events are captured at any time, even if the case has never executed before, or will never execute.  Ok, The events will be captured, but will not be executed until in that case.
    And that's the reason why I have two separate event structures, in two separate phases of the program.
    Because, prior to page 6, the events will occur sequencially. The user will click somewhere, then some message will be transmitted over DataSocket, then some message may come , then again some user action and so on. But, when the user starts using page 6, there will be parallel process of user controls events and actions, and incoming messages and corresponding actions. For this, in the page 6, I need a different kind of execution. So I separated the two event structures.
    At first I thought to have SSM, and then I thought to PC, just because I can have two separate parallel processes - one for user events, and another for messages (because that way I can take maximum advantage of message tracking). But looking at other complexities, I find SSM more appropriate. Can you please tell me how can I have my message loop and events loop parallel to each other and just one event structure?
    You can have a dequeue function in your state machine loop and have it be a consumer loop.  Use a timeout on the Dequeue.  If there is a timeout, have the statemachine execute normally after that perhaps just passing the enum wire straight into the case structure of the state machine.  If it doesn't timeout meaning you got a message, then look at the message that is dequeued and act on it.  Perhaps it means ignoring the enum coming in from the shift register and changing the enum to something else to feed into the case structure of the state machine.  Attached is an example
    Attachments:
    PCDesign[1]_BD.png ‏6 KB

  • XY graph in producer/consumer structure

    Hey there,
    this is my first shot at setting up a producer/consumer structure to operate a power supply (I've posted several questions about it here, but since this is more a Labview programming specific question, I thought this might interest more people). Seems to be working fine when using simple controls. But I also want to display the voltage plotted against time. To get the voltage, I have to send a control to the power supply to get the measurements in answer, get the voltage from there and put it in the graph. Since I can only send one control at a time, I've chosen to queue the "read" state behind every control (so for example, when queuing (or queueing?) "Run", I send "Read" immediatly afterwards so as to start the reading). But of course, every time I send a new control (change parameters for example), the graph is set back to zero. Does anyone know a way around this?
    This is just a tryout, no error handling or even closing of VISA sessions.
    Attachments:
    Producer consumer tryout.vi ‏37 KB

    crossrulz wrote :
    Not really.  Your waits are in parallel, so the delays do not simply add up.  You really should get rid of the 150ms wait that is outside of the case structure.  If you need to introduce any delays, they should be in the specific cases that will need them.
    Well, the power supply doesn't accept commands that come in at a faster rate, so I was thinking that by putting the wait function there, I would manage the queue in a way that it only sends commands at this specific rate. It's only the read function that needs to be executed at specific intervals. All the others don't need to. So I would still delete de 150 ms and put it inside every other command case?
    crossrulz wrote :
    One more comment on your code.  If you have something that needs to constantly happen, I just use the Timeout ability of the queue.  You could just set your timeout to be 500ms and then on timeout it performs a read.  This would eliminate the need to enqueue the Read command at all.
    You mean the timeout abilty of the queue? How would I go about this, create a separate "enqueue element", wire a constant of 500 to the timeout and the read state to the element input, then wire it to the Master Queue? I was thinking of using the timeout ability of the event structure. But I guess that wouldn't be ideal if I have more than one producer loop... Anyways, you Sir, are a genius.

  • Best way to handle this producer-consumer situation

    This is, i'm sure a common thing, however, I never really thought about it before. I can't post my VI so a description will have to do. It should go without saying, but I will repeat it's producer-consumer architecture. Let's say you have a signal generator and all the controls for it are in a cluster. A value changes, fires an event in the producer loop and you compare new and old values to determine which button changed. Cool, all good. So then I queue up a read front panel state in my prodcuer loop which is dequeued in my consumer loop. The read front panel state loads all the new values into a cluster which then is fed into a shift register to be accessed from anywhere in my code (see here).
    Now my question is, what should my next state be that I queue up? If I have a single "send commands to sig gen" state, in my consumer loop I again have to determine which value changed in order to know which command to send (because the original determination of what changed was in the producer loop). However, if I have an individual state for each command I want to send, my case structure will get very big, very fast.
    Final option is have one send command state and just write all data on a single control's value change, whether it's new or not (this seems overkill).
    Suggestions please?
    CLA, LabVIEW Versions 2010-2013
    Solved!
    Go to Solution.

    For situations like this I would not send a "state" to the consumer.  I send a "command."   When the consumer receives a command, it determines whether that command is executed immediately or whether it completes the task in process and then handles the new command.
    Along with the command I send a parameter or parameters.  For your signal generator the parameters would probably be something like a cluster of "control ID" and "value."  The control ID would probably be a typedefed enum and the value a DBL.
    What ever you decide, think about it, plan it, and document it before you code it.
    Lynn

  • Register event in producer consumer design pattern

    Hello wire workers,
    I am fairly green when it comes to dynamic event registration, so my understanding of it is probably quite flawed, but what I have implemented seems to work fine.
    Assuming a fairly typical queued producer/consumer state machine architecture.
    Up till now, I have done the dynamic event registration outside (i.e. to the left of) the UI loop, so all events get registered before the UI loop starts to run.
    My question is:
    How can I register events from inside one of the consumer loops? I cannot wire it...
    Maybe an example will make my scenario more clear.
    I have a DAQ loop (queued state machine). In the init state of this loop I want to register a digital input such that changes on a line are handled by my main event structure (in the totally separate UI loop). Is this possible?
    I look forward to hearing positive answers
    nrp
    CLA

    The best way to send data from the Consumer Loop to the Producer Loop is through User Events. What you will want to do is create a User Event whose data type is the registered DAQmx event refnum. Then when you register the DAQmx event in the Consumer Loop, fire the User Event with that new refnum and update the registration in the Producer Loop. That's probably hard to wrap your head around in words, so I'll attach a dummy example and pic below. Hope this helps!
    VI Saved in LV85.
    Message Edited by Jarrod S. on 04-21-2008 12:54 PM
    Jarrod S.
    National Instruments
    Attachments:
    DAQmx Event.vi ‏30 KB
    DAQmx Event Pic.PNG ‏38 KB

  • Producer consumer control of temperature

    Hello Everyone
    Im using a DAQ 6008, and Labview 8.5 to achieve the following outcome:
    measure the temperature across a heater bank, compare the temperature to set point, using PID, output a analog value - (0 -5) this then is used to control the duty cycle of pwm output in labview (pwm vi)
     I previously tried to write this all into 1 while loop, however due to the slow duty cycle required (1hz) for my output, and the fast sampling of the input I got a 200279 error.
    After reading many forums, I have now converted this to a producer consumer loop. Where the Producer loop, reads the temp, and PID produces an output, it outputs the result to the consumer loop, to create the duty cycle of my pwm output.
    I have a question about the queuing data: My worry is that "old duty" cycle values will be building up in the queue, resulting in a old duty cycles for the pwm output, which do not correspond to the latest as possible temperature - resulting in a unstable control.
    Was hoping some one would be able to clarify this ?
    Thanks/ Dankie

    If you only want the latest data, use a notifier instead.  The notifier can only store a single value.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

Maybe you are looking for

  • Getting error in RWB

    Scenario:file to file Source Structure: 2 fields( Fname & Lname) Target Structure :1 field(Full_name) i m getting below error in RWB when i start sender communication channel. error"Conversion of file content to XML failed at position 0: java.lang.Ex

  • Converting PowerPoints 22"x22" to PDF

    For the obvious reasons, small file size and universal transportability, we're trying to document our products with .pdf files.  Understandably, the simplifications neccessary for these benefits may come with some restrictions. New drawing generation

  • Exchange 2003 to 2010 Migration

    Hello, I seem to have ran into issues with Default GAL, default address lists, email address policies, OAB, etc. Background: Exchange 2003, with one FE and one BE server with multiple domains for mail access. We decided to migrate to 2010 and have on

  • Installing PSE 10 on a mac

    I am running a Mac with OS 10.7.3 an am unable to install PSE10 (retail) as instructed I pop into the drive disc 3,  everything works okay and the installation window opens. I double click Photoshop Elements and the folder opens that conatins the ins

  • Getting good performance from Amazon AWS EBS disks

    Hi, I am new here, so please let me know if I should be posting somewhere else. We are using the Amazon cloud and striped EBS disks for Oracle DB 11g. We have done many tests trying to get good performance from the disks but it is still lacking. I am