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. Thanks

Maybe 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.

Similar Messages

  • 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.

  • 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
    MOHAN

    I 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.

  • Producer - Consumer problem

    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,
    Cochu

    Hi 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 for

    Your 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.

  • Processing acquired data (8 simultaneous channels) in RT host (producer,consumer problem)

    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

  • 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_memory

    What is jtux?
    Use code tags to make your post more legible.

  • Producer consumer problem - semaphores

    problem solved.
    Message was edited by:
    nasher

    The 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.

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

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

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

  • Producer Consumer Start Trigger

    Short Explanation: I'm using a 3rd party device to send a TTL signal to use as my start trigger in my VI. My cDAQ and modules appear to have the ability to send a start trigger independantly but I have been unable to hunt down how to do this in a producer/consumer system.  I do have an idea at the bottom of the long explanation.
    Long Explanation:
    I'm running a test system that monitors the pressure wave from a hydrogen/oxygen ignition. Components are a cDAQ-9188 with modules 9222 (x3 high speed AI), 9481 (x2 relay), 9402  (x1 I/O Module), 9221 ("Low" Speed AI). 
    Based upon recommendations in this forum I've placed my DAQ in a producer/consumer architecture. 
    At this point the system mostly works, I still have a few more things to add for all the information I want to collect. However, it records at high speed and the 9221 and the 9222 modules are synchronized. It has successfully collected good data as of this writing.
    When the system starts it will monitor, but not record. I need to fill the test structure with gas to a specific concentration before I ignite/record. When I press the record button I send a TTL signal from the 9402 to my high speed camera and I close a relay on a 9481 which engages a spark system. The spark system takes a variable amount of time to charge and fire so I have a timer that leaves the TTL and the relay active for a half second.
    My problem, and it's a small one, comes in with the monitoring system and the synchronization. In order to get the system to synchronize properly I had to generate an external pulse into PFI0 to use as a trigger. I attempted to assign the various clocks available as a start trigger but I ended up with unsynchronized data.  
    Is there a way to generate a pulse on my 9402 to use as a trigger? It feels silly to me to use an external device when I have something that can generate the signal I need.
    In thinking about this post I might have solved my problem, at least in my head. I'm thinking I can move the TTL output VI (which I will eventually change to DAQmx) into the producer loop and move my true/false statements to the consumer loop as a 1D array within my queue to start the record. Probably more to it than that but I can only learn by experimentation right?
    Thoughts? Recommendations?
    VI attached. 
    Solved!
    Go to Solution.
    Attachments:
    HUCTA Controls.vi ‏186 KB

    You can't generate a pulse with the 9402 itself. The pulse would actually be generated by the 9188. You should create a Counter Output task to generate a pulse train. Try the attached example as a start point to experiment with the counter.
    This Vi is for LabVIEW 2013, if you have an older version let me know and I will try to convert it.
    Camilo V.
    Applications Engineer
    National Instruments
    www.ni.com/support
    Attachments:
    Pulse Train Generator.vi ‏18 KB

  • Progmatically stop vi with producer/consumer architecture

    I can't seem to get my VI to fully stop, so that I can go on to do some more things in the program.  I am trying to progmatically stop the vi (pictured below), so that I can return to my main gui (not pictured).  The main gui just consists of a login, exit test system, and run test.  Once the user presses run test, the vi pictured below opens.
    I am using a producer/consumer architecture with a state machine.  The problem I run into is that when I press the "Main Menu" button, it should close the pictured vi and return to the main gui.  I tried using the vi server, and when the user presses the Main Menu button, it fires an event and then it goes to the Stop state in the consumer loop, which opens a reference to the vi's (one for the strip chart vi and another for the gage vi), closes the front panel using an invoke node and then closing the reference.  I also tried adding in the abort vi method after the close front panel and it still gave me the same result.
    Here is the catch, it does close the vi's, but it does not stop the while loops (producer and consumer), or it stops only one of the loops.  I thought of putting in a constant in the event structure for when the Main Menu event is fired, but that will stop the producer loop before the consumer loop reveices the info to go to the stop state, so the consumer loop does not end.
    I also tried a "dummy" control that was connected to the comsumer loop Stop terminal (for the while loop), and then progmatically changed the value in the stop case to true and then read that value in the producer loop to, hopefully, stop both loops, but it did not work either.
    I am sure that it is something so stuipidly simple that I cant see it right now
    Kenny
    Kenny
    Attachments:
    test system.gif ‏252 KB

    Hi Kenny,
    I think of two solutions to your problem. First, use the message queue to pass the message "stop" or something from producer to consumer or second (and I think, better), use occurrences. I made a little draft how it could work.
       You have to pass the occurence- Refnum to both VIs, the producer and the consumer, when the producer finishes execution, then use "Set Occurence".
       In the consumer blockdiagram you react on the generated occurrence.
    If you set in the VI- properties "Open Frontpanel when called" and "Close if originally..." the VI Frontpanel should disappear itself when execution is stopped.
    Hope this helps,
    Dave
    Message Edited by daveTW on 08-14-2006 04:53 PM
    Greets, Dave
    Attachments:
    occurrence 1.png ‏1 KB
    occurrence 2.png ‏5 KB

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

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

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

  • Producer consumer timing

    Back again
    Thought I was getting somewhere now I am at another brick wall.
    Bit of background:
    I have a producer consumer set up. In the producer loop there are 2 DAQmx read VI's reading from a Pressure task and a Temperature task. These are multiple channels, 1 sample, outputtng a 1D wave form. This loop is set to run every 20ms. The two tasks were created using DAQmx Create Channel VI's and DAQmx Start Task VI's. The producer loop feeds a display on the front panel with the sensor values and this hopefully is refreshed at the 50Hz I have asked for. Secondly the loop bundles up the waveforms and puts them in a queue where they are picked up for logging by the consumer loop. In the consumer loop I have a wait 1000ms timer and a Write to Measurment File Express VI to do the logging. This is supposed to log at 1 per second.
    The queue is set to enqueue at opposite end, and the max queue length is set to 1. I.E. I only want to log the value at that specific second, but I want to show the data on the front panel at 50 times a second.
    Now heres my problems:
    1) I replaced the DAQmx Create channel's with a MAX project task wired into my DAQmx Start Task VI. As expected the thing picks up and displays the sensor values as it did before. However there is now a problem logging. Before when I had the DAQmx Create Channel, the logging recorded my values correctly at 1 second intervals. The time stamp in the X column went up by 1 second for each set of results. But now, with the MAX project task (needed because of custom scales and differing min/max values for different sensors), The logging still seems to happen at 1 per second, but the time stamp intervals are the same as the sampling rate set in the task!!! (ie at 50Hz the time stamp goes up 20ms for each result even though the results are being recorded at 1 per second)
    2) The timing just seems out of whack.
    I keep getting errors that the requested data no longer exists, that it was there but then was over written. Increasing the buffer size or sampling rate is supposed to remedy this... but what sampling rate? the rate set in the task? or the loop iteration speed? I dont understand.
    Secondly, despite telling my consumer loop to wait one second between picking up stuff out of the queue to log, it seems to be going round nearly the same pace as the producer loop. To top this off the producer isnt going round at the speed I asked it too either! I put indicators on the loop counters to see this. they are going round at maybe 2Hz.
    I have included my VI's
    What am I doing wrong, its really bugging the crap out of me!
    Attachments:
    EngineMon.zip ‏90 KB

    The reason you would use get time and date in seconds to to ensure that you log every second. If you use the 1 second wait then you do not take into account the exicution time of your loop. If you add more to the loop in the future than you will see that you do not log every second as you thought. If you loop took 500ms to exicute and you have the 1000ms wait then the actual excution time for recoding to file is 1.5 seconds not 1000ms as you desired. The way I did it will always give you one second unless you exicution time for your loop exceeds one second.''
    I did make one change to the vi. I shoulod have put the write in the true false case so that the write only happens when the 1 second has expired.
    Tim
    Johnson Controls
    Holland Michigan
    Attachments:
    VDU3.vi ‏59 KB

  • First attempt at Producer Consumer Architectu​re: continuous read and dynamicall​y update parameters​.

    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-Se​rial/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 KB

    Jon,
    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

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

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

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

Maybe you are looking for

  • How to stop the backup process....

    How to stop the backup process.... Okay, so it happens nearly everytime you synch your iPhone with your iTunes? Easy. As soon as it starts, hit the "X" in the bar where the backup process is being shown, this does NOT STOP the synching process, ONLY

  • How Adobe reader will access SAP PKI for digital signatures

    Hello, I am using a ABAP report to upload signed PDF document and validating the signature. However signature which I am using is client side Signature and not the server side. I still hope that I would be able to get these signatures from document.

  • How to Create a Auto Generated number with some preceding text in Sharepoint 2010

    I am trying to create a auto generated number field in Sharepoint 2010 list item. My requirement is to have the following format number generated when new request is created in Sharepoint using form. Auto generated Ticket ID should be in the followin

  • Best approach to upgrade MaxDB AND move to new OS release

    What would be the best approach to upgrade Contentserver MaxDB 7.5 on W2K server (32-Bit) to MaxDB 7.7 on Windows 2008 Server x64 (R2?)? 1.  a) Upgrade MaxDB on the existing installation      b) Create a complete backup      c) Install latest release

  • My IPad Apple ID is disabled. How do I enable it

    I have tried to get my Apple ID enabled, with no luck.  Can you help me.  My email is [email protected] PLEASE HELP....I am unable to update my apps or purchase anything on my I Pad Thank you