Producer Consumer Problem using sockets
Hello,
Can anybody help me how to implement the Producer Consumer Problem using java sockets? Or any resources you've, pls forward it to me
Cheers.
Neg wrote:
You just tell me if there is any means to do it.Yes, Just use a fixed length ArrayBlockingQueue on either end (or both ends) Use offer() to offer more data and this will return false when the queue is full.
Note: the use of a Socket is entirely optional.
Similar Messages
-
Producer/Consumer problem using jtux.
The buffer can only have 10 items which contains 2 integers. But after some time the producer starts to produce and put more than 10 items in the buffer. Here the semaphore is suppose to stop it but it seems that the producer does not care about it and continues to produce items. I have gone through the code many times i cannot see what is wrong.
//BOUNDED_BUFFER CLASS
import java.io.*;
import jtux.*;
public class Bounded_buffer extends Semaphore{
static public void main(String[] args) {
long pid;
int mutex = create(1);
int fullBuffer = create(0);
int emptyBuffer = create(10);
int shmid = Shared_memory.create(84);
long memPointer = Shared_memory.attach(shmid);
Shared_memory.write(memPointer, intToByteArray(4), 4);
int numProd = 5;
int numCust = 10;
try{
for(int i = 0; i<numProd; i++) {
pid = UProcess.fork();
if(pid == 0) {
producer(mutex, fullBuffer, emptyBuffer, memPointer);
Shared_memory.detach(memPointer);
//Thread.sleep(500,0);
System.exit(0);
for(int i = 0; i<numCust; i++) {
pid = UProcess.fork();
if(pid == 0) {
customer(mutex, fullBuffer, emptyBuffer, memPointer);
Shared_memory.detach(memPointer);
//Thread.sleep(500,0);
System.exit(0);
UExitStatus status = new UExitStatus();
for(int i = 0; i<(numProd+numCust); i++)
UProcess.wait(status) ;
}catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
} //try-catch
destroy(mutex);
destroy(emptyBuffer);
destroy(fullBuffer);
Shared_memory.detach(memPointer);
Shared_memory.destroy(shmid);
System.exit(0);
} //end main
static private void producer(int mutex, int fullBuffer, int emptyBuffer, long memPointer) throws Exception{
long pid = UProcess.getpid();
byte[] buffer = new byte[4];
int usedBuffer;
for(int i = 0; i<20; i++) {
wait(emptyBuffer);
wait(mutex);
//Thread.sleep((int)(10*Math.random()),0);
Shared_memory.read(memPointer, buffer, 4);
usedBuffer = byteArrayToInt(buffer);
Shared_memory.write(memPointer+usedBuffer, intToByteArray((int)pid), 4);
Shared_memory.write(memPointer+usedBuffer+4, intToByteArray(i), 4);
usedBuffer = usedBuffer + 8;
Shared_memory.write(memPointer, intToByteArray(usedBuffer), 4);
System.out.println("Item " + i +" produced by " + pid + '\t' + '\t' + "Items in buffer: " + (usedBuffer-4)/8);
signal(mutex);
signal(fullBuffer);
static private void customer(int mutex, int fullBuffer, int emptyBuffer, long memPointer) throws Exception{
long pid = UProcess.getpid();
byte[] buffer = new byte[4];
int usedBuffer, ppid, num;
for(int i = 0; i<10; i++) {
wait(fullBuffer);
wait(mutex);
//Thread.sleep((int)(10*Math.random()),0);
Shared_memory.read(memPointer, buffer, 4);
usedBuffer = byteArrayToInt(buffer);
Shared_memory.read(memPointer+usedBuffer-4, buffer, 4);
num = byteArrayToInt(buffer);
Shared_memory.read(memPointer+usedBuffer-8, buffer, 4);
ppid = byteArrayToInt(buffer);
usedBuffer = usedBuffer - 8;
Shared_memory.write(memPointer, intToByteArray(usedBuffer), 4);
System.out.println("Customer " + pid + " got item " + num + " from " + ppid + '\t' + "Items in buffer: " + (usedBuffer-4)/8);
signal(mutex);
signal(emptyBuffer);
private static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
// helper function to convert an array of 4 bytes to an int.
// This function is needed to read ints from shared memory.
private static final int byteArrayToInt(byte [] b) {
return (b[0] << 24)
+ ((b[1] & 0xFF) << 16)
+ ((b[2] & 0xFF) << 8)
+ (b[3] & 0xFF);
//SEMAPHORE CLASS
import java.io.*;
// jtux is the library that gives the POSIX interface.
import jtux.*;
// This is an interface to the SystemV semaphores that are
// easier to use. The SystemV interface to semaphores is
// very weird and hard to understand. If you're interested
// you can take a look here, but you do not need to understand
// the implementation, just the interface.
abstract class Semaphore {
// Create a new semaphore. value should be its initial
// value. It should be 1 in most cases. It returns a
// handle to the semaphore.
static int create(int value) {
int semid = 0;
try {
semid = USysVIPC.semget(UConstant.IPC_PRIVATE,
1,
UConstant.IPC_CREAT | 00400 | 00200);
USysVIPC.u_semun_int arg = new USysVIPC.u_semun_int();
arg.val = value;
USysVIPC.semctl(semid, 0, UConstant.SETVAL, arg);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
return semid;
// Destroy a semaphore. This will free the semaphore given
// as argument. You should always do this when you're finished
// with a semaphore.
static void destroy(int sem) {
try {
USysVIPC.u_semun semun = new USysVIPC.u_semun();
USysVIPC.semctl(sem, 0, UConstant.IPC_RMID, semun);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
// Operation P on a semaphore. Same operation as wait below. Use P
// if you are familiar with the lectures, and wait if you are familiar with the course
// book
static void P(int sem) {
USysVIPC.s_sembuf wait[] = new USysVIPC.s_sembuf[1];
wait[0] = new USysVIPC.s_sembuf();
wait[0].sem_num = 0;
wait[0].sem_op = -1;
wait[0].sem_flg = 010000;
try {
USysVIPC.semop(sem, wait, 1);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
// Operation wait on a semaphore. Same operation as P above. Use P
// if you are familiar with the lectures, and wait if you are familiar with the course
// book
// Wait for the semaphore. It will block until the semaphore
// is available.
static void wait(int sem) {
USysVIPC.s_sembuf wait[] = new USysVIPC.s_sembuf[1];
wait[0] = new USysVIPC.s_sembuf();
wait[0].sem_num = 0;
wait[0].sem_op = -1;
wait[0].sem_flg = 010000;
try {
USysVIPC.semop(sem, wait, 1);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
// Operation V on a semaphore. Same operation as signal below.
// Use V if you are familiar with the lectures, and signal if you are familiar with the course
// book
static void V(int sem) {
USysVIPC.s_sembuf signal[] = new USysVIPC.s_sembuf[1];
signal[0] = new USysVIPC.s_sembuf();
signal[0].sem_num = 0;
signal[0].sem_op = 1;
signal[0].sem_flg = 010000;
try {
USysVIPC.semop(sem, signal, 1);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
// Operation siganal on a semaphore. Same operation as V above.
// Use V if you are familiar with the lectures, and signal if you are familiar with the course
// book
static void signal(int sem) {
USysVIPC.s_sembuf signal[] = new USysVIPC.s_sembuf[1];
signal[0] = new USysVIPC.s_sembuf();
signal[0].sem_num = 0;
signal[0].sem_op = 1;
signal[0].sem_flg = 010000;
try {
USysVIPC.semop(sem, signal, 1);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
//SHARE_MEMORY CLASS
import java.io.*;
// jtux is the library that gives the POSIX interface.
import jtux.*;
// This is an interface to the SystemV shared memory that are
// easier to use.
// If you're interested you can take a look here, but you do not need to understand
// the implementation, just the interface.
abstract class Shared_memory {
// create creates a new shared memory segment.
// Argument size is the size of the segment in bytes.
// create returns a handle to the newly created
// shared memory segment. When the OS is not able to create a new
// segment, the process is terminated with exit value 1.
static int create(int size) {
String keystring = new String(".");
int shmid = -1 ;
long key;
try {
key = USysVIPC.ftok(".", (int) UProcess.getpid());
shmid = USysVIPC.shmget(key, size, UConstant.IPC_CREAT | 0666);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
return(shmid);
}//create
// destroy removes the shared memory segment in argument.
// If the argument shm is not a valid handle to a shared memory segment
// the process is terminated with exit value 1.
// You should always remove a shared memory segment when you are finished
// with it.
static void destroy(int shm) {
try {
USysVIPC.s_shmid_ds shmds = new USysVIPC.s_shmid_ds();
USysVIPC.shmctl(shm, UConstant.IPC_RMID, shmds) ;
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
}//destroy
// attach "places" the shared memory segment passed in argument
// in the address space of the calling process. This way the process can
// access the segment. A pointer to the the block in the process address space
// is returned.
// If the argument shm is not a valid handle to a shared memory segment
// the process is terminated with exit value 1.
static long attach(int shm) {
long shmaddr = -1 ;
try {
shmaddr = USysVIPC.shmat(shm, 0, 0) ;
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
return(shmaddr) ;
}//attach
// detach "detaches" the shared memory segment at shmaddr
// in the process's address space.
// If there is no shared memory attached at address shmaddr.
// the process is terminated with exit value 1.
static void detach(long shmaddr)
try {
USysVIPC.shmdt(shmaddr);
} catch (Exception e) {
System.out.print("Exception: ");
System.out.println(">" + e.toString() + "<");
System.exit(1);
}//detach
// write : writes into shared memory segment.
// writes at address addr datasize bytes of array data
static void write(long addr, byte[] data, int datasize){
UUtil.jaddr_to_seg(addr, data, datasize);
}//write
// read : reads from a shared memory segment.
//reads datasize bytes at address addr and stores them in
// array data
static void read(long addr, byte[] data, int datasize){
UUtil.jaddr_from_seg(addr, data, datasize);
}//write
}//Shared_memoryWhat is jtux?
Use code tags to make your post more legible. -
Shared memory usage of Producer Consumer Problem
Hai,
I am able to write the Producer-Consumer problem as a interthread communication. But I don't know how to write it using shared memory. (i.e. I wish to start Producer and consumer as a different process). Please help me, sorry for the Temp file idea.
Thanks
MOHANI have read that in the new brightly JDK1.4 you would be able to use shared memory, but I have to confess that I'm not sure about if I'm mixing different informations (lots of stuff read, u know?). Try reviewing the JDK1.4 SE new features.
Also, I should reconsider using "traditional" ways like RMI, Sockets, and things like those.
Regards. -
Calling producer/consumer subvi using main vi for image grab acquire
Hi everyone,
I am not sure if I get the producer/consumer concept wrong. I tried to write a producer/consumer subvi that simulate continuously grab acquire image. When I call the subvi from the main while loop with a main vi, it seems to run into a infinite loop. I am wondering does anyone know how else can I activate a producer/consumer subvi using main vi? Thanks in advance.
Kind regards,
Han Yen
Solved!
Go to Solution.
Attachments:
MainTrial.vi 7 KB
ProducerConsumerGrab.vi 18 KBHi Han Yen,
a few remarks :
- your Top VI has no function what so ever. So skip that.
- your image queue has no name, so that gives problems from the minute you're going to use more queues.
- It does not matter which command you send to the queue, it will start the bottom loop anyway
- You don't have a check whether "live trial" is true yes or no, so everytime you switch it from T=>F or F=>T is will activate the command.
I've tweeked your producer-consumer. Maybe this will give you an idea. I put some remarks in some places
Kind regards,
- Bjorn -
Have fun using LabVIEW... and if you like my answer, please pay me back in Kudo's
LabVIEW 5.1 - LabVIEW 2012
Attachments:
ProducerConsumerGrab.vi 21 KB -
Unsynchronized Producer Consumer Problem
Hi I would like some help implementing an unsynchronized producer consumer with an unbounded queue (implemented using an ArrayList) I have both the producer and consumer sleeping for random amount of time (producer wakes up faster). The problem is that sometimes the producer never gives the consumer a chance to run.
Note I have a notify after I add stuff to the ArrayList. I dont know whether its my choice of collection object or the fact that I have not defined a wait for the producer.
I don't know whether I have explained my problem clearly so feel free to ask some questions. ThanksMaybe I should not have used the word unsynchronized.
But what I am trying to do is have the producer
putting more objects into the buffer than the
consumer can remove. The problem is that my producer
does not let the consumer run ever.The basic model is like this:
// Producer
while (!done()) {
synchronized(queue) {
while (queue.isFull()) {
queue.notifyAll();
queue.wait();
queue.put(next job);
queue.notifyAll():
// Consmer
while (!done()) {
synchronized(queue) {
while (queue.isEmpty()) {
queue.notifyAll();
queue.wait();
job = queue.get();
queue.notifyAll():
process job
}I expect I've missed a subtlety or two in the whole get/put/wait/notify cycle--I always have to reconstruct it from scratch in my head, it's not something I carry around. It should be pretty close though and should show you the main pieces.
As mentioned, if you use the concurrency package, some of that gunk is hidden from you. -
Hi,
Can anyone tell me what is the problem with the below program. Its following the traditional producer consumer concept. For the first time the producer is executed correctly , followed by the consumer printing the consumed value. But for the next time, its hanging at the producer wait loop.
Thanks in advance,
CochuHi All,
I found out the problem. Actually I forgot to put the getShared() method in loop!!!
Cochu -
Producer consumer problem - hanging
Can anyone tell me how to fix this problem? In the code below the producer fills the queue until it reaches capacity (10) and then the consumer takes until it reaches 0 and then waits. It seems they are not running at the same time....I want the producer to be filling the queue each time the consumer takes.
my output:
Clerk ID: 1
Clerk put: 1
Clerk put: 2
Clerk put: 3
Clerk put: 4
Clerk put: 5
Clerk put: 6
Clerk put: 7
Clerk put: 8
Clerk put: 9
Clerk put: 10
customer take9
customer take8
customer take7
customer take6
customer take5
customer take4
customer take3
customer take2
customer take1
customer take0
public class clerk extends Thread{
//declare variables
public ArrayBlockingQueue queue; //create "mailbox"
public int number;
/** Creates a new instance of clerk */
public clerk(ArrayBlockingQueue q1, int num) {
//System.out.println("Clerk created");
queue = q1; //assign queue
number = num; //assign number
}//end clerk constructor
public void run()
long id = getId(); //get threads ID
id = id - 6;
System.out.println("Clerk ID: " + id); //test
int t = queue.size(); //get size
while(t < 10)//while the queue is not full
try {
queue.put(number); //add to queue
t = queue.size(); //get size
System.out.println("Clerk put: " + t); //test
catch (InterruptedException e){ }
}//end while
//}//end for
public class customer extends Thread {
//declare variables
public ArrayBlockingQueue queue; //create "mailbox"
public int number;
/** Creates a new instance of customer */
public customer(ArrayBlockingQueue q1, int num) {
queue = q1; //assign queue
number = num; //assign number
public void run()
long id = getId(); //get threads ID
id = id - 7;
int t = queue.size(); //get size
while(t > 0)//while there is something in the queue
try {
queue.take();
int c = queue.size(); //get size
System.out.println("customer take" + c);
sleep((int)(Math.random() * 100));
catch (InterruptedException e) { }
}//end while
//}//end forYour Clerk class is putting the items in the queue very rapidly (you have no sleep() call in there). Compare that to how you're throttling the Customer implementation. I'd expect Clerk to outrun it given that implementation.
-
Hi Gents,
I have a Crio 9024 and two delta sigma modules NI 9234, I have to acquire 8 cahnnels simultaneously at 51,2 kHz from FPGA and transfert this data via DMA fifo to the RT host for proceesing (FFT for all channels and send data to a host computer via a stream network). I succeed to do this with 25,6KHz as sampling frequency but when I tried with 51,2KHz (my goal) I had problem because in RT code I have a producer loop receiveing data from fpga (DMA fifo) and sending this data to a consumer (Queue) loop in RT also for processing this data but the producer is to fast so the consumer loop can't proccess data in time and the queue is overflow. I have replaced queues with RT fifo,single process variable,... but no luck !!!
Any way how to send 8 channels data from one loop to other for processing (base band FFT N channels) at 51,2KHz ???
Please I need help !!!DMA Fifo:
To avoid overflow you have to configure the RT side which has a default size of 10000 (Rio4.0 and above 2^14 elements) or doubled FPGA depth (fifo_config)
RT Fifo:
config example
Read data from DMA to RT Fifo
(read all elements available and write this data block to your RT fifo, which is configured to hold n-Blocks of size x, i.e. 300Blocks of 18432elements each)
--> here I suggest to read a multiple of 8, because of your channel count
Read data from RT fifo to stream
(send data blocks to the host where each block is one element in terms of streaming buffer --> configure streaming buffer)
Configuring large RT Fifo's has an impact on memory usage, so have an eye on it.
Screens are just examples (not functional code)
Hope it helps
Christian -
Problem using sockets, etc.
Alrighty, well I'm building a very basic chat server using the tutorial from IBM, and when I got to compile it, I get the following (DOS capture):
Server.java:51: warning: [unchecked] unchecked call to put(K,V) as a member of t
he raw type java.util.Hashtable
outputStreams.put(s, dout);
^
.\ServerThread.java:27: cannot find symbol
symbol : class DataIntputStream
location: class ServerThread
DataInputStream din = new DataIntputStream(socket.getInputStream());
^
1 error
1 warning
Not sure what the first one means, and I'm none too sure how to correct the second one. Suggestions?It is a warning you'll get from java 5 and up when you use plain Object types where you would need to use a generic type. Look up "generics" for a more detailed explanation.
-
Hey,
I'm writing a simple client/server app and I'm trying to test it on my local machine. Every time I try to connect to the server I get a ConnectException. I'm running Ubuntu Intrepid (which I suspect may have something to do with my problem).
This is how I'm setting up the server (just to add, this is threaded):
this.socket = new ServerSocket(TCP_SERVER_PORT);
socket.accept(); //blah, blah, blahAnd this is how I'm trying to connect:
this.socket = new Socket("127.0.0.1",TCP_SERVER_PORT);I have no idea why this fails! Any ideas?
Cheers,
Puffejp wrote:
I get a ConnectExceptionwith what message?I get:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:180)
at client.TCPClient.<init>(TCPClient.java:30)
at client.TCPClient.main(TCPClient.java:74)
socket.accept(); //blah, blah, blahYou mean Socket client = socket.accept();That is what I mean, sorry (lazyness! :)).
And this is how I'm trying to connect:
this.socket = new Socket("127.0.0.1",TCP_SERVER_PORT);
That should certainly work on the host the server is running on. Could be your /etc/hosts file. It should map 'localhost' to 127.0.0.1, and your real hostname to your real IP address. This is a common, and rather shocking, problem with some Linux distributions.
127.0.0.1 localhost
127.0.1.1 peter-laptop
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
Also can you post the output of netstat -na after you have started the server.
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN
tcp 1 1 192.168.1.70:57052 72.5.124.102:80 LAST_ACK
tcp 1 0 192.168.1.70:38987 66.102.9.100:80 CLOSE_WAIT
tcp 1 1 192.168.1.70:57047 72.5.124.102:80 LAST_ACK
tcp 1 1 192.168.1.70:57049 72.5.124.102:80 LAST_ACK
tcp 1 1 192.168.1.70:57051 72.5.124.102:80 LAST_ACK
tcp 1 1 192.168.1.70:57050 72.5.124.102:80 LAST_ACK
tcp 1 1 192.168.1.70:57048 72.5.124.102:80 LAST_ACK
tcp6 0 0 :::22 :::* LISTEN
udp 0 0 0.0.0.0:41091 0.0.0.0:*
udp 0 0 0.0.0.0:68 0.0.0.0:*
udp 0 0 0.0.0.0:5353 0.0.0.0:* I've cut out the bit after "Active UNIX domain sockets" because the message was too long, but I have it if it would help.
Does this shed any light on the problem?
Cheers,
Pete
Edited by: Puffy on Jan 9, 2009 10:48 AM -
Producer consumer problem - semaphores
problem solved.
Message was edited by:
nasherThe last one is 'E' a subnetmask for a private LAN of 20 machines
Masking is at the bit level as in binary;-
|||00000.||||||||.||||||||.|||||||| == 224.255.255.255 - mask ---> multicast
||000000.|0|0|0|0.||||||||.|||||||| == 192.168.255.255 - mask ---> Class 'C' Private LANS
- or both, M-cast and Class 'C' Private LANS ;-
||||||||.||||||||.||||||||.|||||||| == 255.255.255.255 - which masks all IP addresses ie: all IP nos.
- in a process called logical AND-ing ie:-
0 + 0 = 0
0 + | = 0
| + 0 = 0
| + | = |
- So, to subnetMASK a private cls C LAN =
||||||||.||||||||.||||||||.||||0000 == 255.255.255.240
- will leave 4 remaining bits to address the subnetwork and binary 0000|||| = (2 pow 4) 16, not enough! - though;-
||||||||.||||||||.||||||||.|||00000 == 255.255.255.224
would = 5 bits = up to 32 (less 2, one=gtw + one=router) machines would've worked.Hope I've been of service, though I'm not 100% sure of the other answers. -
Producer/consumer w/ScanEngine issue
All,
I have a large VI implemented with producer/consumer architecture using 10 events and uses conditional disables to select the data acquisition hardware. The application is being developed in LV2009 with FPGA & RT on XP. The application is intended to acquire and control analog signals in a cRIO-9073, but early development is done using LV simulated signals. I can switch back/forth between the different configurations quickly & easily. In the simulation mode, the front panel, controls, events, etc; all behave as one would expect. When the conditional disable is changed to use ScanEngine and cRIO modules, then a very primary control fails to generate an event and does not function. All other controls that can be tested are functional and generate their events. I am at a loss and seeking suggestions on techniques to diagnose & fix the problem. The application behaves as if the 'event structure' for primary control gets corrupted or some size threshold is been exceeded. The whole concept, scanEngine based and simulated data, were functioning several days ago prior to numeruous edits and I can revert back to not using the scan engine and cRIO hardware with simulated data to validate correct function, but that is not the intended final path. At the present time, I am stuck and looking for ideas. All suggestions will be considered and appreciated. The applicatiion is company proprietary and can't be posted. Thanks in advance.I can definitely understand your confusion, and on the surface it seems like everything should transfer over. However, when using simulated data you won't get errors that can occur once you introduce hardware. Errors can prevent events from occuring, there is also the issue of timing, to see if when using actual hardware, the timing causes issues. As I menationed before, there are a hundred different reasons why it would work with simulated data, but not actual hardware. Please let me know if you need further direction in your troubleshooting.
National Instruments
Applications Engineer -
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);
} -
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 -
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.
Maybe you are looking for
-
Contacts and Personal Ringtones not working correctly.
I have an iPhone 3G with the latest OS. Since I have upgraded to the latest OS, I have had problems with my contacts when I receive incoming calls. On some of my contacts, I will not see the assigned photo or hear the assigned personal tone, it inste
-
Sending attachment from servlet or jsp
Dear Friends, I downloaded javamail api and I have seen the sendfile.java, which is used to send attachments. it is working fine. I can able to run that program from command prompt like this := c:>java sendfile [email protected] [email protected] mail.smtp.net
-
Airplay Icon is missing since i updated to ios5. How do i stream music to pc now ?
-
TS5150 Apple TV and DAC audio converter
I have all Apple products. I am trying to get stereo/audio from AppleTV to the DAC? The DAC line goes to an older Sony stereo receiver. Stereo will play through the TV and Uverse connection, but not when I switch over to AppleTV. I have followed some
-
What should I download as the wireless LAN driver/adapter
When I search for a wireless LAN driver in the hp site there are 8 or more wireless LAN drivers/adapters under different names. I do not know what exactly I need. please help me. I downloaded Mediatek 802.11wireless LAN adapter driver but I couldn't