Is it a proper way to use queue for consumer/producer model?

Hi all,
  I am following the example of consumer/producer model to use the queue to synchronize the following process: The producer is a loop to produce N numbers, I will put every generated number into an array and after every 5 numbers generated, I put the array into the queue and pass it to the consumer. I have to wait the consumer use up the data and it will then remove the element from queue so the producer will get a chance to produce another 5 numbers. Since I set the maximum size of the queue to be ONE, I expect the producer and consumer take turns to produce / consume all five numbers and pass the chance to the other. Here is my code
when the case box is false, the code will be
For the first 5 numbers, the produce will generate every thing right and put that into the array, and it will pass the array to the quere so the consumer will get a chance to loop over the array. I except the procude's loop will continue only when the queue is available (i.e. all elements are removed), but it seems that once the consumer start the loop the produce 's loop will continue (so the indicator x+1 and x+2 will show numbers changed). But it is not what I want, I know there must be something wrong but I can't tell what is it.
Solved!
Go to Solution.

dragondriver wrote:
As you said in 1, the sequency structure enforcing the execution order, that's why I put it there, in this example, to put the issue simple, I replace the complete code with number increase, in the real case, the first +1 and +2 must be executed in that order.
Mikeporter mentioned:
1. Get rid of all the sequence structures. None of them are doing anything but enforcing an execution order that would be the same without them.
So even if you remove the sequence structure, there will be a fixed & defined execution order and that is because LabVIEW follows DATA FLOW MODEL.
Data Flow Model (specifically in context of LabVIEW): A block diagram node executes when it receives all required inputs. When a node executes, it produces output data and passes the data to the next node in the dataflow path. The movement of data through the nodes determines the execution order of the VIs and functions on the block diagram (Click here for reference).
Now in your code, just removing the sequence structure will not make sure that the execution order will gonna remain same but you need to do few very small modifications (like pass the error wire through For loop, before it goes to 'Dequeue Element' node).
Coming to the main topic: is it a proper way to use queue for consumer/producer model?
The model you're using (and calling it as consumer/producer model) is way too deviated from the original consumer/producer model model.
dragondriver wrote:
For the second one, yes, it is my fault to remove that while. I actually start from the example of Producer/Consumer design pattern template, but I didn't pay attention to the while loop in the consumer part.
While loops (both Producer & Consumer) are the essential part of this architecture and can't be removed. You may want to start your code again using standard template.
I am not allergic to Kudos, in fact I love Kudos.
 Make your LabVIEW experience more CONVENIENT.

Similar Messages

  • What is the proper way to use Siri dictation with punctuation, on iPad with Retina Display?

    What is the proper way to use Siri dictation with punctuation, on iPad with Retina Display?
    Thank you!

    From the iPad User Manual:
    Also:
    no space on ... no space off—to run a series of words together
    smiley—to insert :-)
    frowny—to insert :-(
    winky—to insert ;-)

  • What is the proper way to use the write method?

    What is the proper way to use the OutputStreams write method? I know the flush() method is automatically called after the write but i cant seem to get any output
    to a file. The char array contains characters and upon completion of the for loop the contents of the array is printed out, so there is actually data in the array. But write dosnt seem to do squat no matter what i seem to do. Any suggestions?
    import java.io.*;
    public class X{
    public static void main(String[] args){
    try{      
    FileReader fis = new FileReader("C:\\Java\\Test.txt"); //read chars
    FileWriter fw = new FileWriter("C:\\Java\\Test1.txt"); //read chars
    File f = new File("C:\\Java\\Test.txt");
    char[] charsRead = new char[(int)f.length()];
    while(true){
    int i = fis.read(charsRead);
    if(i == -1) break;
    // fw.write(charsRead); this wont work
    // but there is infact chars in the char Array?
    for(int i = 0; i < charsRead.length -1 ; ++i){
    System.out.print(charRead);
    }catch(Exception e){System.err.println(e);}

    Sorry to have to tell you this guys but all of the above are broken.
    First of all... you should all take a good look at what the read() method actually does.
    http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read(byte[], int, int)
    Pay special attension to this paragraph:
    Reads up to len[i] bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len[i] bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.
    In other words... when you use read() and you request say 1024 bytes, you are not guaranteed to get that many bytes. You may get less. You may even get none at all.
    Supposing you want to read length bytes from a stream into a byte array, here is how you do it.int bytesRead = 0;
    int readLast = 0;
    byte[] array = new byte[length];
    while(readLast != -1 && bytesRead < length){
      readLast = inputStream.read(array, bytesRead, length - bytesRead);
      if(readLast != -1){
        bytesRead += readLast;
    }And then the matter of write()...
    http://java.sun.com/j2se/1.3/docs/api/java/io/OutputStream.html#write(byte[])
    write(byte[] b) will always attempt to write b.length bytes, no matter how many bytes you actually filled it with. All you C/C++ converts... forget all about null terminated arrays. That doesn't exist here. Even if you only read 2 bytes into a 1024 byte array, write() will output 1024 bytes if you pass that array to it.
    You need to keep track of how many bytes you actually filled the array with and if that number is less than the size of the array you'll need pass this as an argument.
    I'll make another post about this... once and for all.
    /Michael

  • What's the proper way to use reusingView in a custom UIPickerView

    Does anyone have an example of the proper way to use the resuingView parameter when implementing pickerView:viewForRow:forComponent:reusingView: in a UIPickerViewDelegate?
    The documentation states that reusingView is "A view object that was previously used for this row, but is now hidden and cached by the picker view."
    and: "If the previously used view (the view parameter) is adequate, return that. If you return a different view, the previously used view is released. The picker view centers the returned view in the rectangle for row."
    I need to create UILabel views so I can right justify things, and I have that working by always returning my copy of the view, but it seems like things could be made more efficient by returning the view passed to me if it's "adequate". So, how do I tell if the view is adequate?
    I've tried something like this:
    // check to see if the view we're given is a UILabel and return that view
    if ([view isMemberOfClass:[UILabel class]])
    v = (UILabel *)view;
    return v;
    else
    ... return a UILabel instance for this row ...
    But the view I'm being passed is never a UILabel instance. That or I'm not using isMemberOfClass correctly.
    Thoughts anyone?

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    iPregnancyAppDelegate *iPregAppDelegate = [[UIApplication sharedApplication] delegate];
    UILabel *pickerLabel = (UILabel *)view;
    // Reuse the label if possible, otherwise create and configure a new one
    if ((pickerLabel == nil) || ([pickerLabel class] != [UILabel class])) { //newlabel
    CGRect frame = CGRectMake(0.0, 0.0, 270, 32.0);
    pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    pickerLabel.textAlignment = UITextAlignmentLeft;
    pickerLabel.backgroundColor = [UIColor clearColor];
    pickerLabel.text = @"Put YOUR text here!";
    return pickerLabel;
    Message was edited by: gpmoore

  • What is proper way to report suggestions for app features And bugs to Apple

    What is the proper way to report suggestions for app features to Apple? Or, do they even want suggestions?
    And, how about reporting app bugs? Should I just assume the bug is already known, or is there a way for (quickly) reporting them?

    I'm not sure about bugs in non-Apple apps, but bugs in Apple apps can be reported via this form:
    http://www.apple.com/feedback/ipad.html

  • Is there any way to use a For Each Loop for each property of an User Defined Type?

    Is there any way to use a For Each Loop for each property of an User Defined Type? That would be very handy!
    Jorge Barbi Martins ([email protected])

    Alas, no, not in VBA.
    Regards, Hans Vogelaar (http://www.eileenslounge.com)

  • Proper way to use data throughout a class?

    I know global variables aren't a thing in c#, as that goes against the rules.
    So I have a couple of functions and subroutines (pardon my vocabulary if it isn't canon). I use a simple array to transfer data back and forth. Is this the proper way to do this? As in most efficient, readable, and expandable?
    class Program
    static void Main()
    bool[] MotorPosition = new bool[4];
    MotorPosition[0] = true;
    MotorPosition[1] = false;
    MotorPosition[2] = true;
    MotorPosition[3] = false;
    while (true)
    MotorPosition = UpdateMotorPosition(MotorPosition);
    DisplayMotorPosition(MotorPosition);
    System.Threading.Thread.Sleep(64);
    static bool[] UpdateMotorPosition(bool[] MotorPosition)
    bool[] NewMotorPosition = new bool[4];
    for (int x = 0; x < 4; x = x + 1)
    NewMotorPosition[x] = !MotorPosition[x];
    return NewMotorPosition;
    static void DisplayMotorPosition(bool[] MotorPosition)
    string CombinedDisplay = null;
    for (int x = 0; x < 4; x = x + 1)
    CombinedDisplay = CombinedDisplay + MotorPosition[x].ToString();
    Console.WriteLine(CombinedDisplay);
    Mediocre Access 2010 | (Baby) Beginner C Sharp | OK at Active Directory (2012) | Fragmented understanding of DNS/DHCP | Laughable experience with Group Policy | Expert question asker on MSDN Forums

    Absolutely amazing! I learn something new every day. I wonder when programming will cease to amaze me.
    using your example jdweng, I was able to add a counter to your code and move the motor position to the test class; as well as add another motor by instancing the class again!
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ConsoleApplication1
    class Program
    static int Main(string[] args)
    Test test = new Test();
    test.Initialize(); //Assigns initial value to MotorPosition
    Test test2 = new Test();
    test2.Initialize(); //Assigns initial value to MotorPosition
    while (true)
    if (test.MotorUpdateCount == 40) Console.ReadLine(); //pauses at 40 to make it easy to see output upto that point
    if (test.MotorUpdateCount > 1000) return -1; //ends program
    test.MotorPosition = test.UpdateMotorPosition(test.MotorPosition); //updates motor 1 position
    test.DisplayMotorPosition(test.MotorPosition); //displays motor 1 position
    if (test.MotorUpdateCount > 20) //at count 20, engages motor 2
    test2.MotorPosition = test2.UpdateMotorPosition(test2.MotorPosition); //updates motor 2 position
    test2.DisplayMotorPosition(test2.MotorPosition); //displays motor 2 position
    System.Threading.Thread.Sleep(128); //slows the loop down to reasonable speed
    public class Test
    public int MotorUpdateCount = 0;
    public bool[] MotorPosition = new bool[4];
    public void Initialize()
    MotorPosition[0] = true;
    MotorPosition[1] = false;
    MotorPosition[2] = true;
    MotorPosition[3] = false;
    public bool[] UpdateMotorPosition(bool[] MotorPosition)
    bool[] NewMotorPosition = new bool[4];
    for (int x = 0; x < 4; x = x + 1)
    NewMotorPosition[x] = !MotorPosition[x];
    MotorUpdateCount = MotorUpdateCount + 1;
    return NewMotorPosition;
    public void DisplayMotorPosition(bool[] MotorPosition)
    string CombinedDisplay = null;
    for (int x = 0; x < 4; x = x + 1)
    CombinedDisplay = CombinedDisplay + MotorPosition[x].ToString();
    Console.WriteLine(CombinedDisplay);
    Console.WriteLine(MotorUpdateCount.ToString());
    Mediocre Access 2010 | (Baby) Beginner C Sharp | OK at Active Directory (2012) | Fragmented understanding of DNS/DHCP | Laughable experience with Group Policy | Expert question asker on MSDN Forums

  • Best or proper way to Use a Mophie Helium with iPhone 5s

    What would be the recommended way to use a Mophie Helium with a iPhone 5s?  Use the phone battery as primary and recharge from the Mophie as needed or use the Mophie battery first and then the iPhone? The later is what Mophie shows in their ops manual but I would like to hear Apples opinion on the issue.

    Based on this http://www.mophie.com/shop/iphone-5/juice-pack-helium-iphone-5, it would not appear that using the Morphie first is what is recomended. since it is essentailly a charging mechaism, frankly, that wouldn't make any sense.
    BTW: this is a user-to-user forum, so Apple will not offer an opinion here.

  • Proper way to use JMenuBar?

    I want to use a JMenuBar to produce some "redundant" functionality into my program. Say, for instance, the user wants to print something. I can have a print button on screen an a print option in the file menu. I can have both objects call a static printRecords() menu in one of my other classes. This part isn't a problem.
    The problem I think I'm going to run into is JMenu items that try to reproduce the functionality of actions in classes that it doesn't have access to. Say, for instance, I have a JPanel full of JTextFields and it also has a button that says "Clear Fields." Currently, my design has the implementation for the button in the JPanel class. This works except that the JMenu does not have access to this method.
    What's the best approach to reducing the amount of code that I have to reuse without passing information all over the place?

    Assuming you still care about this issue (or that others do), I know I'm coming back long time after...
    The only class that I extend is the JPanel class because it makes it easier
    to create and manage the complex layout that I need.
    Are you suggesting there is a better way (...) without extending JPanel?Yes.
    Write business logic in non-graphic classes, write interaction logic into dedicated classes (depending on swing API but not extending any JComponent), and write the building and wiring of graphical components to the intercation classes in a dedicated composer class (you're right I made up this term, I don't know if a generally accepted one exists).
    I looked up the term "composer class" but couldn't find anything.
    Can you go into more detail about this term?Something along the line of:// Simple class, one text field, one clear button
    public class MyGUIComposer
      public void JFrame composeScreen()
      JFrame theFrame = new JFrame();
      JPanel mainPanel = new JPanel();
      mainPanel.setLayout(...)
      JPanel subPanel1 = new JPanel();
      final JTestField myTextField = new JTextField(...);
      Action buttonLogic = new ClearAction(myTextField);
      JButton clearButton = new JButton(buttonLogic);
    }With ClearAction.actionperformed() methods being as simple as the TextField.cleartext();
    If the configuration of the screen is more complex (e.g. lots of text fields, other widgets,...), you can use a Mediator class (this one is a known and documented design pattern). See below.
    Also, I figured I could use the same Action for the different components
    but (...)
    how would a "Clear" Action have a handle to the fields it needs to clear?It should have a handle to a Mediator object: this latter has already references to all widgets. And the clear action does not even bother clearing all buttons but just ask the Mediator to do so.
    The Mediator can itself be the composer, in this case the creation of the action becomes:
           Action buttonLogic = new ClearAction(this); // this being the mediator instanceand ClearAction.actionPerformed() becomes as simple as
    public void actionPerformed() { theMediator.clearAllFields();}And of course you write the mediator class with the method clearAllFields() which iterates through all relevant fields and clears them.
    At first it looks much more convoluted, but the Mediator really comes handy when you add features to your UI : more widgets, more interactions, more conditions (e.g. clear button clears all fields and adds a message in the status bar, and greys out the submit button only if the "Enable empty names" option is false.
    I find it better than having a JPanel subclass having to pass around the value of all options.

  • What if I didn't charge my mac all the way before using it for the first time?

    Okay, so I got my Macbook for Christmas this past year (Mid 2011 model) and of course I was screaming my head off with excitement.
    I powered it up, starting using it for a little bit, then plugged it in to keep it going. I didn't charge it all the way to 100%, I think I was using it for about three hours while it was plugged in and up for the first time. That night, however, it did charge all the way and I don't see any problems with my battery, but I wouldn't know if it was operating at full capacity if the capacity I've been using this whole time has been lowered.
    Thanks!

    Ahh.. okay?
    I was just curious because they all say to charge it fully for the first time.. didn't know if this did anything to the battery or not.

  • Is there a way to use Labview for Linux for IBM AIX 5.1.

    I think any application built for linux can run on the AIX 5.1 if the application is recompiled on the AIX 5.1. So theoretically NI can just recompile there Linux version of Labview on the AIX 5.1 and it will work. Is there a possibility that NI will port Labview for AIX 5.1.

    I think that the use of LabVIEW for linux is platform independent as far as hardware. I believe that as long as you are running a compatible GUI (I believe XWindows and KPT??? are two that are recommended - check ni.com/linux for more information. So, for your purposes, as long as you can install the proper GUI, and then LabVIEW for Linux, you can then run, code, compile, and deploy applications on the AIX 5.1.
    I am personally VERY interested in knowing about your success (or failure, should that unlikelyhood occur) on Linux. If you browse the topics, there is actually one on non-windows useage of LabVIEW. I am currently setting up my first Linux machine at my home office, and am very curious to know how other people do with this 'adventure into unc
    harted territory'. The only documented useage I have seen is in Gary Johnson's newest edition of Power Programming.
    Good luck, and please keep us posted. I sense that I am the only LabVIEW for Linux fan besides yourself. But please feel free to post to this thread, and to the topic.

  • Proper way to use multiple pop-up dialogs

    I've got an application that uses a series of pop-ups to process user information.
    A general flow of information is
    User clicks a button
    ->dialog launches asking for confirmation to start process
    Dialog returns and system processes request (in a returnListener)
    ->System launches new dialog, using AdfFacesContext.launchDialog, asking user to confirm changes to be made
    Dialog returns and systems processes changes.
    What I've noticed is that if I interact with the components in the second dialog 'too much' then the second return listener is not being called.
    So, my question is, am I using dialogs properly? Should I try to use actions and navigation links instead of opening and closing dialogs?

    Sounds reasonable.
    In that vein, is there a way to create 're-usable' dialogs? Ideally I don't want to have to write tons of little dialog that do nothing more interesting than asking "Are you sure?" with the actions set differently.
    At first glance, I'm almost tempted to pack a method binding into the process scope and have the dialog check if it exists, and if it does, execute that. But that seems somewhat, inelegant.
    Any thoughts?

  • Proper way to use a compressor

    I have a bass line that is sitting well in the mix when I put the channel fader to -12 db.
    But there are ocassional peaks that take the signal into Red.
    So before I apply compression to this track should I first put the channel fader down until the signal stops going in the red? Or do I leave the channel fader as it is and then go ahead and mess with the compressor?

    In this case, the answer is clear. Adjust your levels first.
    If you try to fix this using only compression, it will totally flatten anything above the threshold point. That will cause a substantial loss of dynamic range. Far better to maintain that dynamic range since that will make the line more vibrant and musical.
    So, take the level down a touch and apply a compressor. Keep listening and adjusting. By the way, you might like to try using Channel EQ in the path before a compressor. That way, you can take the level down of certain frequencies and still keep the ones that you need in your mix.
    Just to be quite clear, though, the fader operates after all the inserts have done their stuff. When you move the fader down, you're not taking down the signal and then applying compression. What you're doing is taking the hot spots out of the signal with the compressor and then using the fader to mix the treated signal.
    If you really want to take the signal down before applying compressor, use channel EQ (which will, of course change the flavour of your sound) or use the Gain insert (found under Insert > Utility) before the Compressor insert.
    Pete

  • Proper way to use cpCmndExit

    Hello all:
    I am attempting to create a "fast Exit" button. On Success, the button is calling an Advanced Action called QuikExit. QuiKExit is a Standard Action and is structured as
    Assign cpCmndExit with 1
    From what little I can find, this should elicit an exit to the movie but when I publish and try it, NADA!
    Any Ideas as to what I am missing?

    Hi there
    The PDF may not recognize that Captivate is the only thing inside of it. As a result, something like a command to close the window may be ignored from something like Captivate because there could be other content inside the PDF. So in my own guess here, it's more of a PDF security thing.
    I'll also speculate that only a member of the Captivate development team can really answer or explain that in better technical detail.
    Cheers... Rick
    Helpful and Handy Links
    Captivate Wish Form/Bug Reporting Form
    Adobe Certified Captivate Training
    SorcerStone Blog
    Captivate eBooks

  • Right way to use generics for cellular automatons?

    Hi,
    i've got a question about using generic types in combination with subclassing (which should be used in a cellular automaton),
    In fact there are only 3 classes that are necessary to understand my problem:
    - Cell (abstract)
    - CellularAutomaton
    - SubclassedCell (extends Cell)
    These classeses work as follows:
    A cellular automaton holds some cell's with respect to the order they were added. The cell itself holds some properties and the most important function in this small "framework". This function is "performCellAction(CellularAutomaton ca)". It retrieves the "neighbor" cells from the given parameter and calculates a new state using these neighbors.
    The way i implemented this using generics is:
    public class CellularAutomaton<T extends Cell>{
      private List<T> cells;
      public T getLeftNeighbor(T cell) { ... } // gets the left neighbor of the given cell
      public T getRightNeighbor(T cell) { ... } // gets the left neighbor of the given cell
    public abstract class Cell [
      public void performCellAction(CellularAutomaton<? extends Cell> ca) {}
    public class SubclassedCell extends Cell {
      private String str;
      public void performCellAction(CellularAutomaton<? extends Cell> ca) {
        Cell left = ca.getLeftNeighbor();
        // PROBLEM:
        // How to call left.getStr() here???
        // How can i be sure that ca contains objects of class subclassedCell (or objects of subclasses of subclassedCell) ... and not objects of class cell or another subclasses cell
      public String getStr() {}
    }In fact i found "something like a solution", which looks like this:
    public class CellularAutomaton<T extends Cell>{
      private List<T> cells;
      public T getLeftNeighbor(T cell) { ... } // gets the left neighbor of the given cell
      public T getRightNeighbor(T cell) { ... } // gets the left neighbor of the given cell
      public void computer() {
        for (T cell: cells) {
          // compiler warning here!!
          cell.performCellAction(this);
    public abstract class Cell<T extends Cell<?>> [
      public void performCellAction(CellularAutomaton<T> ca) {}
    public class SubclassedCell extends Cell<SubclassedCell> {
      private String str;
      performCellAction(CellularAutomaton<SubclassedCell> ca) {
        SubclassedCell left = ca.getLeftNeighbor();
        left.getStr(); // works here
      public String getStr() {}
    }However, even in this "working" solution i get a compiler warning at the method CellularAutomaton->computer():
    The warning is Type safety: The method performCellAction(CellularAutomaton) belongs to the raw type Cell. References to generic type Cell<T> should be parametrized and Cell<T extends Cell<?>> also looks very uncommon to me.
    Is there a betted way to achieve the goal to access left.getStr() in the performCellAction of the subclassed cell??
    Regards,
    Niko

    I thought of that myself, but if i do this, i get the following error:
    The method performCellAction(CellularAutomaton<capture#1-of ?>) in the type Cell<capture#1-of ?> is not applicable for the arguments (CellularAutomaton<T>)

Maybe you are looking for

  • XL Reporter Report Job

    I'm trying to prepare a report job in XL Reporter that will produce the last quarter's and YTD's value for the specified report definition. My report definition has a parameter that let's the user choose the current financial period and the comparati

  • Mp3 as background audio on web page does not play in ff 3.6.22 It does play in IE why?

    I am building a web page. When I was editing the page and clicked on browser review, the music I was playing in the background played in ff 3.6.22 and in IE 7. When I uploaded the page to the web for testing, the background music played in IE7 but no

  • Nested sequences change aspect ratio of clips underneath them

    Premiere Pro 6.0.5 Mac Book Pro Retina See attached screen shots: 1. Nested sequence is off - everything under is is crisp and proper aspect ratio 2. Nested sequence is on - everything under it is blurry and wrong aspect ratio 3. Only nested sequence

  • One of my notes disappeared

    One of my notes disappeared before my eyes.

  • Invoice Output in OIOXML format

    Hi Experts, I have a requirement to send out Invoices in OIOXML format. How can this be achieved ? Any info on this is highly appreciated.