Producer Consumer Thread
Dear All,
I'm having problems withthe following code, basically i want all the Producer and Consumer threads to terminate by dying naturally in a controlled fashion.
Is there a way that the consumer will know when to terminate consuming from the buffer?
Here i was trying to say that it wshould do so when the buffer is equal to 0, i'm a bit confuse and a lot of help as i have "deadlock" in my brain!
Regards,
Chirag
public class SharedBuffer extends CircularBuffer
private Object sharedObject = null;
private boolean writeable = true;
private boolean readable = false;
private int pCounter = 0;
private int pItems = 0;
private boolean StopProducing;
public SharedBuffer(int b)
super(b);
// put an item in the buffer
public synchronized void put (Object itemBuffer, int i, boolean sp)
while ( !writeable ) {
try {
System.out.println(" Waiting to Produce ");
wait();
catch ( InterruptedException e ) {
System.out.println( e.toString() );
sharedObject = itemBuffer;
pItems = i;
StopProducing = sp;
super.put (sharedObject);
pCounter++;
readable = true;
System.out.println("SharedBuffer.Put: " + super.toString() + "\n");
if ( isFull() )
writeable = false;
System.out.println( "Buffer Full" );
notifyAll();
// remove an item from buffer
public synchronized Object get()
while ( !readable ) {
try {
System.out.println( "Waiting to consume" );
wait();
catch ( InterruptedException e ) {
System.err.println(e.toString() );
writeable = true;
super.get();
if(StopProducing)
pCounter--;
else
pCounter = pCounter - pItems;
System.out.println("SharedBuffer.get: " + super.toString());
if ( isEmpty() )
readable = false;
System.out.println( "Buffer empty" );
notifyAll();
return sharedObject;
public int getPCounter()
return pCounter;
import java.util.Calendar;
public class TimeStampServer extends Thread
// Create a TimeStamp
Calendar now = Calendar.getInstance();
public void run()
setDaemon( true );
while (true) {}
public String getTime()
String timestamp = new String( now.get(Calendar.HOUR_OF_DAY) + ":" +
now.get(Calendar.MINUTE) + ":" +
now.get(Calendar.SECOND) + ":" +
now.get(Calendar.MILLISECOND));
return timestamp;
public class ThreadDescriptor
private String id;
private String group;
private int pri;
private String time;
public ThreadDescriptor(Thread td, String t, ThreadGroup grp)
id = td.getName();
group = grp.getName();
pri = grp.getMaxPriority();
time = t;
public String toString()
String output = "";
output += "[ID = " + id + " | GRP = " + group + " | PRI = " + pri
+ " | TIME = " + time + "]";
return output;
public class Producer extends Thread
private SharedBuffer pSharedBuffer;
private int pItems;
private TimeStampServer pTimeStampServer;
private int seconds;
private ThreadGroup pThreadGroup;
private boolean StopProducing = false;
public Producer(String name, SharedBuffer sb, int items, TimeStampServer
tss, int sec, ThreadGroup tg)
super(name);
pSharedBuffer = sb;
pItems = items;
pTimeStampServer = tss;
seconds = sec;
pThreadGroup = tg;
// activate the thread
public void run()
System.out.println(getName() + " Thread Started\n" );
for (int i = 0; i < pItems; i++ )
try {
Thread.sleep( (int) ( Math.random()* (seconds * 1000) ) );
catch ( InterruptedException e ) {
System.err.println( e.toString() );
ThreadDescriptor td = new ThreadDescriptor( this, pTimeStampServer.getTime(),
pThreadGroup );
System.out.println(getName()+ ".put: " + td.toString());
pSharedBuffer.put(td, pItems, getStopProducing());
System.out.println( getName() + " produced " + pItems + " items \n");
StopProducing = true;
public boolean getStopProducing()
return StopProducing;
class Consumer extends Thread
private SharedBuffer cSharedBuffer;
private ThreadGroup cThreadGroup;
private int cItems = 0;
public Consumer(String str, SharedBuffer sb, ThreadGroup tg )
super(str);
cSharedBuffer = sb;
cThreadGroup = tg;
public void run()
System.out.println(getName() + " Thread Started\n" );
while (cSharedBuffer.getPCounter() == 0)
try {
Thread.sleep( (int) ( Math.random()* 5000 ) );
catch ( InterruptedException e ) {
System.err.println( e.toString() );
System.out.println(getName()+ ".get: " + cSharedBuffer.get() + "\n");
yield();
cItems++;
System.out.println( getName() + " retrieved " + cItems + " items \n");
public class ThreadManager
public static void main(String args[])
SharedBuffer sb = new SharedBuffer(5);
TimeStampServer tss = new TimeStampServer();
ThreadGroup groupProd1 = new ThreadGroup("ProdHigh");
ThreadGroup groupProd2 = new ThreadGroup("ProdLow");
groupProd1.setMaxPriority(8);
groupProd2.setMaxPriority(3);
Producer prod1 = new Producer( "Prod1", sb, 5, tss, 3, groupProd1 );
Producer prod2 = new Producer( "Prod2", sb, 5, tss, 2, groupProd1 );
Producer prod3 = new Producer( "Prod3", sb, 5, tss, 3, groupProd2 );
Producer prod4 = new Producer( "Prod4", sb, 5, tss, 1, groupProd2 );
ThreadGroup groupCons = new ThreadGroup("Consumer");
Consumer cons1 = new Consumer( "Consumer1", sb, groupCons );
Consumer cons2 = new Consumer( "Consumer2", sb, groupCons );
Consumer cons3 = new Consumer( "Consumer3", sb, groupCons );
prod1.start();
prod2.start();
prod3.start();
prod4.start();
cons1.start();
cons2.start();
cons3.start();
ouch!! and that deadline is tomorrow, hope u get the answer
Similar Messages
-
Producer Consumer (Threads)
I had written the following program pasted below . When I try to execute this program I get the error as Canot Resolve Symbol
symbol : constructor Consumer(ProducerConsumer)
location: class Consumer
Consumer c = new Consumer(pc);
^
Similarly for Producer.
I want everything in one class so i am using the dataobject in the mainclass itself and then passing that object to the 2 thread constructors so that they can in their run method call the get and put methods which are basicaly synchronised
Please help me as to where am i going wrong...
import java.lang.Thread;
import java.io.*;
class Producer extends Thread{
private ProducerConsumer dob;
public void Producer(ProducerConsumer c){
dob = c;
public void run(){
for (int i=1;i<10;i++){
dob.put(i);
System.out.println("The value put by thread " + this.getName() + "is" + i);
class Consumer extends Thread{
private ProducerConsumer dob;
public void Consumer(ProducerConsumer c){
dob = c;
public void run(){
for (int i=1;i<10;i++){
int result = dob.get();
System.out.println("The value got by thread"+ this.getName() + "is ");
//dicy exit
System.exit(0);
public class ProducerConsumer extends Thread{
public static void main(String[] args){
ProducerConsumer pc = new ProducerConsumer();
Consumer c = new Consumer(pc);
c.start();
Producer p = new Producer(pc);
p.start();
private int value;
private boolean flag;
public synchronized int get(){
while (flag == false){
try {
wait();
System.out.println("Consumer is waiting");
catch (InterruptedException e) {}
flag = false;
notifyAll();
return this.value;
public synchronized void put(int value){
while (flag == true){
try {
wait();
System.out.println("Producer is waiting");
catch (InterruptedException e) {}
flag = true;
this.value = value;
notifyAll();
}public void Consumer(ProducerConsumer c){Constructors are methods that do not have a return type. So change the line above to
public Consumer(ProducerConsumer c){
public class PC{
private int value;
private boolean flag;
public synchronized int get(){
while (flag == false){
try {
wait();
System.out.println("Consumer is waiting");
} catch (InterruptedException e) {
flag = false;
notifyAll();
return this.value;
public synchronized void put(int value){
while (flag == true){
try {
wait();
System.out.println("Producer is waiting");
} catch (InterruptedException e) {
flag = true;
this.value = value;
notifyAll();
public static void main(String[] args){
PC pc = new PC();
Consumer c = new Consumer(pc);
c.start();
Producer p = new Producer(pc);
p.start();
} -
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.
-
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 KBthisoldman,
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) -
Hello,
I am currently working with two instruments; an Agilent E3646A and an NI 6212 BNC. My objective is to have the 6212 to be continuously taking measurements according to predefined parameters while the E3646A's parameters can be continuously updated. This simple instrument combination is intended to help me learn the necessarry achitecture; continuous measurement, dynamic output control, and more instruments will be added in the future.
I've previously posted on a similar, but more complicated, setup (http://forums.ni.com/t5/Instrument-Control-GPIB-Serial/Split-second-lag-when-controlling-two-instrum... and was advised to try the Producer Consumer Architecture. I've found relevant literature on the site (http://www.ni.com/white-paper/3023/en/, https://decibel.ni.com/content/docs/DOC-2431), searched the forums and constructed my own VI. While my first attempt at a Producer Consumer Architecture has resolved some of the issues I was having when I first posted on the subject, however, new issues have arisen with regard to reading and stopping the VI.
I am currently able to run the VI and update the device parameters. Previously, I would get a freeze while the instrument was being updated and could not toggle parameters until it was done. This has been resolved although the read only updates when a parameter has been updated although it is outside of the event structure. Furthermore the Stop button does not work in any context. I've also gotten occasional errors regarding the Deqeue Element but the bulk of the trouble is Error -200279 "Attempted to read samples that are no longer available" at DAQmx Read. I realize that there is a problem in my Producer Loop but haven't been able to figure out how to resolve it.
This is my first attempt at a Producer Consumer Architecture and already I can see that it is a powerful tool. I read as much as I could and looked at the relevant examples but expected to have some issues in the beginning. Would really appreciate any advice so I can take full advantage of the architecture.
Hope to hear from you,
Yusif Nurizade
Solved!
Go to Solution.
Attachments:
DCe3646A_DAQ6212_Prod_Con_4_13a_2014.vi 89 KBJon,
Thank you for the response and the suggestions.
I created the Local Variable for the Stop Button and moved the original into its own Event Case. It is now able to stop VI execution although I get Warning -1073676294 which I understand to be the buffer issue. The warning says that this was incurred on VISA Open for the E3646A's Initialize VI which is outside both loops, however, which I don't understand.
I tried increasing buffer size by decreasing the Number of Samples as per suggestions I found on NI forum threads. I've brought it down as low as 1 but the graph still only updates when an Event occurs and I keep getting the same buffer error. You suggested that the problem could be that they are in the same loop; does this mean that the DAQmx read should be outside both Producer and Consumer Loops or moved into the Consumer Loop? I found a couple of links ( http://forums.ni.com/t5/LabVIEW/Producer-Consumer-Design-Pattern-DAQmx-Event-Structure/td-p/2744450 , http://forums.ni.com/t5/LabVIEW/Producer-Consumer-Architecture/td-p/494883 -first response) on dealing with an Event Structure that my own VI is based. Alternatively, I found another link ( http://forums.ni.com/t5/LabVIEW/Producer-Consumer-Design-Pattern-DAQmx-Event-Structure/td-p/2744450 - first response) on a DAQmx Read with an Event Structure that places the graph in the Consumer Loop.
The core of my purpose in setting up this Producer Consumer Architecture is so that I could read continuously while the instrument parameters are updated dynamically so it's very important that I understand how this works. I am particularly struggling with how the Event Structure is controlling the While Loop's Execution.
Hope to hear form you,
Yusif Nurizade
Attachments:
DCe3646A_DAQ6212_Prod_Con_4_14a_2014_Edit_I.vi 90 KB -
Running subVI in parallel with itself using producer-consumer pattern
I'm using the procuder-consumer pattern to create what I call threads in response to various events much like in Producer Consumer with Event Structure and Queues
I have several physical instruments, and would like to run the exact
same test in parallel on each of the instruments. I have a subVI
that takes as inputs a VISA resource and a few control references among
other things and then performs the desired experiment. I have a
separate consumer loop for each physical instrument, with this subVI
inside each consumer loop.
My test VI worked great; each consumer loop was a simple while loop
incrementing a numeric indicator (not using my real subVI above).
However, my real program can only run one consumer loop at a time much
to my dismay. Reworking my simple test VI to use a subVI to
increment the indicator rather than just explicitly coding everything
resulted in the same problem: only a single consumer loop ran at a time
(and as I stopped the running loop, another would get a chance to
begin). The subVI in this case was extremely
simple taking only a ref to the indicator and a ref to a boolean to
stop, and incrementing the indicator in a while-loop.
Is there a way around this? Now that I've spent the time making a
nice subVI to do the entire experiment on on the physical instrument, I
thought it would be fairly trivial to extend this to control multiple
instruments performing the same experiment in parallel. It seems
only one instance of a given subVI may run at one time. Is this
true? If it is indeed true, what other options do I have? I
have little desire to recode my subVI to manually handle multiple
physical instruments; this would also result in a loss of functionality
as all parallel experiments would run more or less in lock step without
much more complexity.
Thank you.You need to make your subvi reentrant. Then it can run several instances at any time with each instance occupying its own unique memory space. Click on File - VI Properties - Execution, and check the reentry execution checkbox. Then save the vi.
- tbob
Inventor of the WORM Global -
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 KBVaibhav 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 -
Producer/consumer architecture - timing
Hello.
I have some question about producer consumer pattern.
People say that consumer shound NOT add elements into producer queue. Lets say that some states in in consumer need to stay active for eg 5 minutes. We also should be able to pause/resume state execution and exit program in any time.
I ve used functional global timer but consumer adds elements into queue and this should be avoided.
How to solve timing problem? Some people have written about creating another thread - watchdog or asynchornous calls to vi...
Could someone explain this to me? :People have consumers add to their own queue all the time. It is usually in a Queued State Machine though. If you have a process that just needs to run for so long, then have the consumer run another while loop until the time is up. It can then process the next item in the queue.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
Timed structure for output in producer consumer data acquisition
Hello LabVIEW community,
I have a bit of a problem. I am writing a program that is primarily for data aquisition but has a few control features as well. I need the program to aquire and write several channels of data at a relitively high speed. The program does this fine ( in the top 3 loops fo the program). I need the program to also send a seires of two output signals in response to a particular condition. When a certain channel registers a value of above a specified number, I need an output channel to write an anologue signal for 225 seconds and then a signal of a differnt value to the same channel untill the condition occurs again (not for several hours).
I put this action in a timed structure inside of a case structure. The case structure and timed structure are inside of a second consumer loop. I have no idea if this is ligitimate. This event takes much longer than any of the other loops which run at 1 or 2 seconds. When I exicute the program with "highlight exexutuion" this longer (case/ timed ) loop never executes. I asssume this has to do with the mismatch in time scales of this loop and the other loops in the program. I also didn't really understand the help information on timed structures, so its possible that I just need better/ different inputs to the timed stuctures.
If anyone can see any obvious problem in the code or suggest a better way to do the output function I would really appreciate the help. My code is attached.
Thanks,
JoI can't figure out how to fix your code, but I can point out the things I see wrong with it.
1. You are dequeueing elements from the same queue in the same loop. In one you are not taking the element, and in parallel, you are taking an element. I see that in your bottom two loops. Why? That code won't execute until the queue gets two elements in it. And which dequeue gets it first and which gets it second is an arbitrary race condition. So there is no certainly of order (first 4 vs. last 4 currents in the one loop), or which gets kept and which gets discarded (in the other loop.)
2. You are creating and/or clearing DAQ tasks in every loop iteration. Tasks should be created before a loop, used inside the loop (read or write), then cleared once the loop is done. Anything else is wasteful, time consuming, and could lead you to run out of resources.
3. You are using the STOP function which is pretty much like hitting the abort button on the toolbar. No program should ever stop that way. All loops should exit gracefully.
4. You have a data dependncy between your bottom two loops because of the boolean wire running from one to the other. That bottom loop will only run once (if the value is True), or run forever (if the value is false).
5. Use of the dynamic datatype. You are taking waveforms, converting them to a blue wire, then coercing them into another datatype such as just displaying a scalar in an indicator. A lot of unnecessary conversions there.
6. Your thermometer indicators have a digital display you can make visible. Then you won't need the separate numeric indicator to display the value.
7. For loop that runs only 1 time because of the constant wired to the N terminal. Get rid of the For Loop.
8. Check your spelling. The word "Temperatures" on the graph, and one instance of "distillate" is missing an "l".
Until all of these problems are fixed, it is not worth talking about timing of timed structures. Some of these problems were discussed in your other thread. http://forums.ni.com/t5/LabVIEW/producer-consumer-missing-channels/m-p/3159757#M911255 But now it seems like you've made things even more complicated without fixing the basic problems. -
AJAX producer/consumer and JAVA producer/consumer in same project
I've already successfully integrated and customized the code for both an AJAX and JAVA producer/consumer client in JMS (using ActiveMQ as the JMS broker and Tomcat as the webapp container). While both have been working well in separate projects, unfortunately, I'm having a bit of trouble trying to integrate them for the purpose of running an AJAX message listener and JAVA message listener in the same project.
What I'm trying to do is have JAVA act as the failover for when the AJAX JMS consumer is not listening (i.e. when the browser is closed). When a browser client opens, the (constantly running) JAVA client can ignore the messages... but... when no browser client is initialized, the JAVA client should respond to the messages on behalf of the AJAX client.
I've tried using a ServletContextListener pattern, which I was hoping would "automagically" launch the JAVA listener via its main method, whenever the Servlet gets initialized (i.e. it would auto-start when Tomcat gets restarted, or, anytime the Servlet gets redeployed) but it seems Tomcat is not thread-safe and this might be causing some problems.
In any case, I can't seem to get the JAVA client to reliably start running and stay running for the lifetime of my AJAX client (webapp .war), and without including them in the same project and same J2EE container sharing the same ServletContext, I don't know how its possible to ensure they are running and starting and stopping at the same time.
Is there perhaps a better way to accomplish this?
Edited by: bcmoney on May 17, 2010 1:25 PMI've already successfully integrated and customized the code for both an AJAX and JAVA producer/consumer client in JMS (using ActiveMQ as the JMS broker and Tomcat as the webapp container). While both have been working well in separate projects, unfortunately, I'm having a bit of trouble trying to integrate them for the purpose of running an AJAX message listener and JAVA message listener in the same project.
What I'm trying to do is have JAVA act as the failover for when the AJAX JMS consumer is not listening (i.e. when the browser is closed). When a browser client opens, the (constantly running) JAVA client can ignore the messages... but... when no browser client is initialized, the JAVA client should respond to the messages on behalf of the AJAX client.
I've tried using a ServletContextListener pattern, which I was hoping would "automagically" launch the JAVA listener via its main method, whenever the Servlet gets initialized (i.e. it would auto-start when Tomcat gets restarted, or, anytime the Servlet gets redeployed) but it seems Tomcat is not thread-safe and this might be causing some problems.
In any case, I can't seem to get the JAVA client to reliably start running and stay running for the lifetime of my AJAX client (webapp .war), and without including them in the same project and same J2EE container sharing the same ServletContext, I don't know how its possible to ensure they are running and starting and stopping at the same time.
Is there perhaps a better way to accomplish this?
Edited by: bcmoney on May 17, 2010 1:25 PM -
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?
ThanksThrown 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 Design error?
I am learning labview as I go and little errors keep stumping me. I set up the producer/consumer design and it reads the two while loops like I want. However, when I stop the program to save it to the write to measure it gives me an error saying invalid input and highlights the dequeue. I have to queues running (one for a button and one for data) and they both do this. I tried connecting it different ways but its always the same error. Any ideas?
Attachments:
2whlloopprgrm.vi 392 KBDublicate post
Stick to one post at a time. Do not post the same question on two different threads. -
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. -
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);
} -
Using BlockingQueue for Producer - Consumer
I am trying to use the BlockingQueue in a Producer-Consumer
pattern instead of creating a Q and using wait() and notify().
The output what I want is:
Put : 1
Got : 1
Put : 2
Got : 2But the output I am getting is :
Put 0
Put 2
Put 4
Got 3
Got 5
Got 7This is my Java code using BlockingQueue
Have I missed any point?
Can I not use BlockingQueue instead of using wait() and notify()?
class Producer2 implements Runnable {
private BlockingQueue<String> queue;
public Producer2(BlockingQueue<String> q){
this.queue = q;
public void run(){
int i=0;
while(true){
try {
String putValue = Integer.toString(i++);
queue.put(Integer.toString(i++));
System.out.println("Put " + putValue);
} catch (InterruptedException e) {
e.printStackTrace();
class Consumer2 implements Runnable {
private BlockingQueue<String> queue;
public Consumer2(BlockingQueue<String> q){
this.queue = q;
public void run(){
while(true){
try {
String value = queue.take();
System.out.println("Got " + value);
} catch (InterruptedException e) {
e.printStackTrace();
public class ProducerConsumer_BlockingQueue_Test {
public static void main(String[] args) throws Exception {
BlockingQueue<String> q =
new LinkedBlockingQueue<String>();
Thread p1 = new Thread(new Producer2(q));
Thread c1 = new Thread(new Consumer2(q));
p1.start();
c1.start();
}Nothing to do with the queue, in your producer you're incrementing i twice, once after seting putValue, again after queuing the item.
Maybe you are looking for
-
My mac fall and now the trackpad is not working?
So today my macbook fall and the bottom left part of the trackpad is not working . I can still move the cursor, but if I click on the bottom left corner of the trackpad, I cannot tap the other trackpad part, it will not respond. To make it respond ag
-
Master-Detail Form (How to pass an item value in Master to Detail field
I have a Master-Detail form. When adding a new record in the Detail section, I expect the primary key in the master record will copy down to the detail record. But, it is not doing that. Does anyone know how to pass the master primary key down to the
-
How to find who has deleted pograms .
Hi experts. Suppose U have created a program and after certain time you found that, the program is deleted by some one and now it does not exits. In this case, how can one found that who has deleted the program by using the program name. I mean ther
-
DESIGN VIEW in blocks, dashed lines
I'm using DW CS5.5. Up until today, design view was working. Now I'm getting everything in blocks with dashed lines surrounding it. I have no idea how this happened or how to get it to go back to a usable design view. Live View is working, but I
-
Is there any way to execute a custom script after JPA created tables?
Hi I am looking for a way to execute some scripts right after JPA created the tables. I want the script to be executed once and not every time my application start. I though maybe Toplink has some extensions for this. Thanks.