Multithreading in JavaFX

Hello

I need to work with multiple threads in a JavaFX application. I have a screen with 10 buttons and I need to "connect" each thread with the key that started the thread. If the user press a button that had begun a thread (in the main, MainController.java), I need to recover to view the information that contains to post it on the controls (a second screen, DetailController.java) details screen.


What class do you recommend for this? Service?

https://docs.Oracle.com/javase/8/JavaFX/API/JavaFX/concurrent/package-summary.html


It is possible to name the son with one of these classes?


Best regards

-javier

Use an executor, for example

Executors.newSingleThreadExecutor () to have a single background thread, used for all buttons.

You can pass a custom, ThreadFactory to create Threads, which have names.

Then use either the task or a JavaFX Service (create them on JavaFX Thread).

Service, you can setExecutor, for affect your executor.

With the task, you simply call executor.execute (yourTask);

Services and tasks are similar. Services can be restarted and create something new every time. Tasks are more like' one-time' and can only be used once.

use the stateProperty() to listen to changes, for example, FAILURE or SUCCESS, and update your user interface then.

Tags: Java

Similar Questions

  • Multithreading in JavaFx program.

    I'm new to JavaFx and I'm trying to JavaFX 2.0 version.

    I created a simple Progressbar demonstration program.
    To set the progress in the progress bar ((value), I use thread as evidenced by the program below.
    I also try EventQueue.invokeLater for animation in the progressbar control. but I don't understand.

    Please let me how can know I get the animation using wire to the JavaFX 2.0 program.

    SerializableAttribute public class ProgressFx extends Application {}

    volatile private ProgressBar pBar;
    pIndr of volatile private ProgressIndicator;

    Public Shared Sub main (String [] args) {}

    Launch (args);
    }

    @Override
    public void start (point primaryStage) bird Exception {}

    Root of group = new Group();

    Scene = new scene (root, 450, 300, Color.WHITE);

    progressBarDemo (root);

    Thread t = new Thread (new ProgressRunner(), 'progress test');
    t.Start ();

    primaryStage.setScene (scene);
    primaryStage.setTitle ("Progress Bar Demo");
    primaryStage.show ();
    }

    {} private void progressBarDemo (root of Group)

    pBar = new ProgressBar (0);
    pBar.setPrefSize (200, 30);

    pIndr = new ProgressIndicator (0);
    pIndr.setPrefSize (100, 100);

    HBox hBox = new HBox();
    hBox.setSpacing (10);
    hBox.setPadding (new INSET (25, 3, 3, 10));
    hBox.setAlignment (Pos.CENTER);

    hBox.getChildren () .add (pBar);
    hBox.getChildren () .add (pIndr);

    root.getChildren () .add (hBox);
    }

    int i = 0;

    /**
    *
    */
    the class ProgressRunner implements Runnable
    {
    public void run() {}

    for (i = 0; i < 101; i ++) {}
    try {}
    Thread.Sleep (500);
    System.out.println (i);
    EventQueue.invokeLater (new Runnable() {}

    public void run() {}

    pBar.setProgress(i/100);
    pIndr.setProgress(i/100);
    }
    });

    } catch (InterruptedException ex) {}
    System.out.println ("Exception:" + ex.getMessage ());
    }
    }

    }
    }

    }

    Published by: user11242282 on December 11, 2011 21:05

    Below, I've corrected the part of code that has been given to your boredom. Here are some tips:

    (1) use Platform.runLater instead of EventQueue.invokeLater. The first is for running things on the JavaFX event queue, while the second is for the Swing/AWT event queue.

    (2) property of the ProgressBar advances is a double. However you were completing this value to an integer (even after having divided by 100, the result will be an integer and get rounded to zero). I fixed that by dividing by 100.0, which is a double.

    (3) instead of being using the volatile to contain references to the controls themselves, whereas instead linking the progression of the control property to your private property. For example:

      private final DoubleProperty myProgress = new SimpleDoubleProperty(0.0);
    
      ... then later:
    
      pBar.progressProperty().bind(myProgress);
      pIndr.progressProperty().bind(myProgress);
    
      ... and in the update code simply do:
    
      myProgress.set(i / 100.0);
    

    In any case, replace the code in the update with the following corrected version and it will work.

      class ProgressRunner implements Runnable
      {
        @Override
        public void run() {
          for(i = 0; i < 101; i++) {
            try {
              Thread.sleep(500);
              System.out.println(i);
              Platform.runLater(new Runnable() {
                @Override
                public void run() {
                  pBar.setProgress(i / 100.0);
                  pIndr.setProgress(i / 100.0);
                }
              });
            }
            catch(InterruptedException ex) {
              System.out.println("Exception: " + ex.getMessage());
            }
          }
        }
      }
    
  • looking for best practices on the display of the data inside a TableView

    I have an app that can extract one ore more of 300,000 lines as a result of a request, and I am their display in a TableView... I use a mechanism to bring the data "off-site", when I do the query, an object with the ID of the lines is set in memory and a 'queryResultKey' went to start asking for the data set.
    The controllers send the queryResultKey saying the DAO that she already results N, the DAO will return X records (from N + 1 to N + J) or less if the total number of records is reached. At this point, records are added to the elements of the table view using an addAll to list related to the itemsProperty table.
    It works very well for early records already, but all of a sudden a Null pointer Exception is raised:
    ene 15, 2013 12:56:40 PM mx.gob.scjn.iusjfx.presentacion.tesis.TablaResultadosController$5 call
    SEVERE: null
    java.lang.NullPointerException
         at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:291)
         at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:48)
         at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.callObservers(ReadOnlyUnbackedObservableList.java:74)
         at javafx.scene.control.TableView$TableViewArrayListSelectionModel$3.onChanged(TableView.java:1725)
         at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:134)
         at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:48)
         at com.sun.javafx.collections.ObservableListWrapper.callObservers(ObservableListWrapper.java:97)
         at com.sun.javafx.collections.ObservableListWrapper.clear(ObservableListWrapper.java:184)
         at javafx.scene.control.TableView$TableViewArrayListSelectionModel.quietClearSelection(TableView.java:2154)
         at javafx.scene.control.TableView$TableViewArrayListSelectionModel.updateSelection(TableView.java:1902)
         at javafx.scene.control.TableView$TableViewArrayListSelectionModel.access$2600(TableView.java:1681)
         at javafx.scene.control.TableView$TableViewArrayListSelectionModel$8.onChanged(TableView.java:1802)
         at com.sun.javafx.scene.control.WeakListChangeListener.onChanged(WeakListChangeListener.java:71)
         at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:291)
         at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:48)
         at com.sun.javafx.collections.ObservableListWrapper.callObservers(ObservableListWrapper.java:97)
         at com.sun.javafx.collections.ObservableListWrapper.addAll(ObservableListWrapper.java:171)
         at com.sun.javafx.collections.ObservableListWrapper.addAll(ObservableListWrapper.java:160)
         at javafx.beans.binding.ListExpression.addAll(ListExpression.java:280)
         at mx.gob.scjn.iusjfx.presentacion.tesis.TablaResultadosController$5.call(TablaResultadosController.java:433)
         at mx.gob.scjn.iusjfx.presentacion.tesis.TablaResultadosController$5.call(TablaResultadosController.java:427)
         at javafx.concurrent.Task$TaskCallable.call(Task.java:1259)
         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
         at java.util.concurrent.FutureTask.run(FutureTask.java:166)
         at java.lang.Thread.run(Thread.java:722)
    This exception multibordure inside the Thread that fills the table:
    task = new Task<Integer>() {
                @Override
                protected Integer call() throws Exception {
                    while (listaTesis.size() < pag.getLargo()) {
                        List<TesisTO> tesisParaincrustar = fac.getTesisParaLista(pag.getId(), listaTesis.size());
                        try {
                            listaTesis.addAll(tesisParaincrustar);
                        } catch (Exception exc) {
                            Logger.getLogger(TablaResultadosController.class.getName()).log(Level.SEVERE, null, exc);
                        }
                        tesisActuales.addAll(tesisParaincrustar);
                        updateProgress(listaTesis.size(), pag.getLargo());
                    }
    
                    return new Integer(100);
                }
    
                @Override
                protected void succeeded() {
                    status.getProgreso().setVisible(false);
                    preparaFiltros();
                    llenandoTabla = false;
                    tblResultados.getSelectionModel().select(0);
                }
            };
            status.getProgreso().progressProperty().bind(task.progressProperty());
            new Thread((Runnable) task).start();
    So that may be another strategy to simulate (or have) all the registry values are in memory and 'capture only the necessary links' to display them in the TableView?
    Any idea will be useful.

    The first thing I would do here is to check that

    fac.getTesisParaLista(pag.getId(), listaTesis.size())
    

    cannot return null in all circumstances. If it returns null, then it is the source of your exception. In this case, you must add the caution appropriate to your code:

    if (tesisParaincrustar != null) {
                        try {
                            listaTesis.addAll(tesisParaincrustar);
                        } catch (Exception exc) {
                            Logger.getLogger(TablaResultadosController.class.getName()).log(Level.SEVERE, null, exc);
                        }
                        tesisActuales.addAll(tesisParaincrustar);
    }
    

    For the number of thread, you can plan everything which modifies the user interface to run on the Thread of the FX Application using Platform.runLater (...). Note that any data that you pass into that must not be changed elsewhere. If you can do something like:

    Platform.runLater(new Runnable() {
      @Override
      public void run() {
                        try {
                            listaTesis.addAll(tesisParaincrustar);
                        } catch (Exception exc) {
                            Logger.getLogger(TablaResultadosController.class.getName()).log(Level.SEVERE, null, exc);
                        }
                        tesisActuales.addAll(tesisParaincrustar);
      }
    });
    

    You need to add the 'final' keyword to the declaration of tesisParaincrustar to get this to compile.

    That's fine, assuming that the call to fac.getTesisParaLista (...) returns a new instance of the list each time (i.e. it does not change an existing list).

    You'll end up with only one problem: the condition in your while loop (...) refers to listaTesis.size (). Given that this list is now updated on a different thread to the thread of the while loop (...) management. This can (and probably won't be) cause the loop to terminate at the wrong time. You can adjust the condition while (...) so it does not refer to this list (for example, advance calculate how many things must be read, give this number to your implementation of the task and use it in the while condition (...).)

    There are actually two rules for multithreading in JavaFX:
    1. do not access the user interface outside the FX request Thread. This includes data related to the user interface structures. I guess at some point you have called tableView.setItems (listaTesis), so listaTesis should be considered as part of the user interface.
    2. don't run long running on the Thread of the FX Application tasks.

    In trying to comply with rule 2, you have violated rule 1.

    The incremental updates to a list that appears in a background thread is one of the most delicate uses of the task. Read the documentation of the API for task (http://docs.oracle.com/javafx/2/api/javafx/concurrent/Task.html): the example of "PartialResultsTask" under "a task that returns partial causes" is an example of what you're trying to do.

  • Why almost all javafx methods must be called from the thread of the application?

    I have a pretty big 3D scene that is refreshed every few seconds.

    It takes a while to update the scene, and I wanted to do it in a background thread.

    Problem is that almost every approach I take requires the application-fx thread.

    Now, I understand that change the UI itself must be called in the application thread, so I tried a different approach:

    Create a new group, add all the nodes (which takes the greatest amount of time) and update the component root of the view with the new group.

    I assumed that only the last party required the application thread, but alas this was not the case.

    group.getChildren () .add also requires that the thread of the application. Why?

    node.setLayoutX () also requires that the thread of the application. Why?

    It is a new set of nodes that are not visible and groups yet, so why can't do this in a background thread?

    The reasons of principle (I think) that JavaFX is mainly a single toolbox threaded are described in:

    https://weblogs.Java.net/blog/2004/10/19/multithreaded-toolkits-failed-dream

    That said, if you manipulate objects that are not part of an active scene, then it should work.  The dream that failed has what to do with the components who participate actively in the molten, interactive GUI.  If you're interacting with only the components out of the screen, then it (should be) without issue.

    Please, create and post an example minimum, executable that replicates the question.

    (Please ensure that the example is minimal and executable).

    In addition, what is the cause as your application "takes some time to update the scene?  Computers are today quite incredibly fast.  Of course, there are valid reasons for some things take time, I wonder what these are in your case.  What is the time?  If your executable example can include something reasonably representative of what you're done which shows something that will take "some time", would be great.

    What you have described so far, I feel that, even if there is no problems with threads, your proposed approach would not fix your performance problem.

  • Dynamic forms of JavaFX

    I want to create a form that dynamically shows/hides input fields.

    For example, I have a RadioButton control, which will cause, according to the selected value of a text box to display (using a translation & transitions melted). If the option button has no control below then they will be moved down to make room for the text box, if the value of "trigger" in the ToggleGroup of the radio buttons is changed then hide the text box (using transitions) and move all the controls until taking up the space of the text box.

    Help (or examples) will be appreciated.

    There is a nice overview of the Animation (timeline and Transitions) here: http://docs.oracle.com/javafx/2/animations/basics.htm

    The basic idea is that a timeline changes the value of one or more properties on a specified time interval. You can consider a property as an object that holds a value. In JavaFX properties are "observable", which means that other objects can register to be notified when they change. Controls to respect their own properties, and if a change is made which means the control should be re-posted, it schedules a request to be re-posted. For example, the text box in the example I posted has a maxHeight property. Changing the value of the maxHeight property causes the text box itself to be notified, and it appears again. There are some smart logic in there to make sure that if a property is changed several times during a single "pulse" of the thread managing the actual repaints, that all changes are gathered in the last modified.

    So to animate an effect going down, simply create a schedule that changes the value of the maxHeight property, and the maximum height will be increased from a value of zero (leading to no space in your page layout) to the size you need. (The code I post below calculates the size is actually a bit problematic, has a bit of a hack to do.) There are some subtleties to worry about to to do with multithreading here, but class Timeline and other related classes take care of all these subtleties for you.

    The mechanics of how you create a timeline is as follows. You start by creating a bunch of objects KeyValue. Each KeyValue specifies a property must be set and give it a value. So, let's create a KeyValue specifies the text box maxHeight property and a value of 0; and an another KeyValue specifies the same property and a value that represents the final height, we want the text to be box. The KeyValues to create a sequence of keyframes. Each keyframe contains a KeyValue (property and the value at which it set) and a time during which reach the KeyValue. Finally, create a calendar with a collection of keyframes. Play() is called on the timeline, it sets all the properties, he knows their keyValues to 0 and then gradually are modified to meet each value specified at the appropriate time specified by all keyframes. In your case, it is quite simple: a keyframe for a duration of zero and a key value setting the property maxHeight to zero and a keyframe at the end of the transition (say 500 milliseconds) with a key value affecting the maxHeight value target. To hide the text box, simply play a timeline with the reverse key values.

    To create an animation "fade out", you can create a calendar that changes the value of the opacity property. Since this is a very common effect, there is a FadeTransition class that does exactly this. You build it specifying a node that has withered, and specify the value "" (opacity of departure) and 'to' value (ending opacity).

    To run two or more transitions one after the other, use a SequentialTransition and transitions to be executed in order. To run two or more simultaneously, use a ParallelTransition. I'll show a ParallelTransition that allows to run a FadeTransition simultaneously with the transition changing the maxHeight.

    The only tricky part here is to find what to set the maxHeight when the text box is fully displayed (i.e. the target value at the end of the transition). The default maxHeight for a text box (and many other controls) is the special value Control.USE_COMPUTED_SIZE. This means that the size should be calculated based on the requirements of the control. The real value, it takes the value is negative (I think-1), and animating from 0 to-1 obviously will not achieve the desired effect. The height is not actually calculated until the control is added to a scene and displayed in a stadium. Approach (somewhat ugly), so that we will take is to add the text box to the scene in the usual way, view the scene, ask the textArea for its height and save in a variable, and then reset the maxHeight of the text box. Note This will not work if you use FXML and you try to do this in the initialize() method (the text box will not appear in a stage at this point). In this scenario, you can either register a listener for the changes made to the height property and set a variable duration, the first, you get something meaningful. For a text box, it's probably good enough to make a reasonable determination for height (8 + 16 * number of desired lines, for example). The right text box displays additional lines if there is too much space and use scrollbars if there is not enough. For other controls, it can be a little more important to do things.

    import javafx.animation.FadeTransition;
    import javafx.animation.KeyFrame;
    import javafx.animation.KeyValue;
    import javafx.animation.ParallelTransition;
    import javafx.animation.Timeline;
    import javafx.application.Application;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.RadioButton;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.ToggleGroup;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class DynamicForm extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        final VBox form = new VBox(10);
        final VBox choices = new VBox(5);
        final RadioButton male = new RadioButton("Male");
        final RadioButton female = new RadioButton("Female");
        final RadioButton other = new RadioButton("Other");
        final ToggleGroup toggleGroup = new ToggleGroup();
        toggleGroup.getToggles().addAll(male, female, other);
        choices.getChildren().addAll(male, female, other);
        final TextArea otherText = new TextArea();
        otherText.setPrefColumnCount(40);
        otherText.setPrefRowCount(3);
        otherText.setPromptText("Please specify");
        final VBox otherBox = new VBox();
        otherBox.getChildren().add(otherText);
        final HBox buttons = new HBox(10);
        buttons.getChildren().addAll(new Button("OK"), new Button("Cancel"));
    
        form.getChildren().addAll(choices, otherBox, buttons);
    
        // otherText.maxHeightProperty().bind(
        // Bindings.when(other.selectedProperty())
        // .then(Control.USE_COMPUTED_SIZE).otherwise(0));
    
        Scene scene = new Scene(form, 300, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    
        final double textHeight = otherText.getHeight();
    
        other.selectedProperty().addListener(new ChangeListener() {
          @Override
          public void changed(ObservableValue observable,
              Boolean oldValue, Boolean newValue) {
            final Duration duration = new Duration(500);
            FadeTransition fade = new FadeTransition(duration, otherText);
            KeyValue sizeStart;
            KeyValue sizeEnd;
            if (newValue) {
              fade.setFromValue(0);
              fade.setToValue(1);
              sizeStart = new KeyValue(otherText.maxHeightProperty(), 0);
              sizeEnd = new KeyValue(otherText.maxHeightProperty(), textHeight);
            } else {
              fade.setFromValue(1);
              fade.setToValue(0);
              sizeStart = new KeyValue(otherText.maxHeightProperty(), textHeight);
              sizeEnd = new KeyValue(otherText.maxHeightProperty(), 0);
            }
            Timeline animateSize = new Timeline(new KeyFrame(new Duration(0),
                sizeStart), new KeyFrame(duration, sizeEnd));
            ParallelTransition transition = new ParallelTransition(fade,
                animateSize);
            transition.play();
          }
        });
        System.out.println(textHeight);
        otherText.setMaxHeight(0);
        otherText.setOpacity(0);
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    }
    
  • 13 Firefox works in multithreaded mode and it can use the quad-core processors?

    When you buy a new PC, we choose between dual core vs quad core processors, and some people claim that Firefox work mode multithreaded mulch and treats each tab in a separate process and may fully use the advantage of a quad-core processor. Is this true?

    Firefox does not treat each tab in a separate process. If this can be a function in the future, I don't know of any plans to introduce any time soon. Obviously, buying a quad core processor will be significantly faster than a dual core, and your browser is usually less consume a lot of resources than other programs. I would not use it as your buying decision. Firefox will work just as well on a dual-core or a quad-core, but windows and other programs will work better with 4 cores.

  • Multithreading and partitioned shared memory

    Hi all

    I'm having no success with this problem multithreading (simple?) on my processor core-i7, using CVI 9.0 (32-bit compiler).

    In the snippets below, I have a structure of node 5 integers, and I use 32 calls to calloc() to allocate space of 32 blocks of 128 * 128 nodes (16K) and store pointers returned in a table as a global var.

    Size in bytes of the nodes = 20, size in bytes of the block = (roughly) 328KB, total allocated size in bytes = (roughly) 10.5 MB.

    I have then spawn 32 threads, each of them is passed a unique index in the pointer_array of 'node_space' (see code below), kind, each thread handles (read/write) a block separated from K 16 knots.

    It must be thread-safe and multiply by the number of threads because each thread is addressing a different memory block (with no overlap), but not multithreading go more quickly (maybe a little) to a single thread.

    I tried different sizes of thread pool, filling of the nodes to the limits of 16 to 64 bytes, all to nothing does not.

    Is this a problem of band bandwidth memory due to the size of the tables? Each thread is somehow loaded the whole 32 blocks?  Any help appreciated.

    struct node

    {
    unsigned int a;
    unsigned int b;
    unsigned int c;
    unsigned int d;
    unsigned int e;

    } ;
    typedef struct lymph nodes;
    typedef nodes * Node_Ptr;

    Node_Ptr node_space [32];          / * pointer to table in 32 separate blocks (loaded via individual calloc calls for each block) * /.

    .... Spawning wire...

    for (index = 0; index)< 32;="">

    CmtScheduleThreadPoolFunction (my_thread_pool_handle, My_Thread_Function, & index, NULL);

    Hello CVI_Rules,

    It is difficult to answer your question because it depends on what you do in your thread function. Given that you do not see any speed upward in your program when you change the number of threads in your thread pool, you are done as well (or all the work) in each thread, serialize your threads with locks, or somehow slow down execution of each thread.

    Your basic configuration seems fine. You can simplify it slightly by moving the nodes directly to your thread function:

        for (index = 0; index < 32; ++index)
        {
            CmtScheduleThreadPoolFunction(pool, My_Thread_Function, node_space[index], NULL);
        }
    
    ...
    
    static int My_Thread_Function(void *functionData){    Node_Ptr nodes = functionData;...
    

    But this will not affect performance.

    Things to look at:

    1. Check that you're really work only on a subset of node space in each thread, you are passing and receiving the correct node space in each thread and you work only on that one.
    2. Verify that you do not have locks or other synchronization in your program. It seems that you do not have because you have designed your program so that it would not need any. But check anyway.
    3. Check that you do not have something useless in your thread function. Sometimes people call ProcessSystemEvents or ProcessDrawEvents because they feel that it makes the user interface more responsive. These two functions are expensive (all about 20 ms per call, I think). So, if you call these functions in a loop, with a fixed number of iteraction on all threads, and if the actual calculations are relatively fast, then these functions can easily dominate the runtime of your program. (There aren't necessarily those functions, it may be others. "These are just examples).
    4. Show and explain your code to a colleague. Sometimes, you don't see clearly until you show someone. Or they may have noticed something.

    Apart from this, can you explain what you are doing in your thread function so that we can have a better understanding of your program and what might inhibit parallelism?

  • Multithreading and interactions with instruments

    I have to start by saying that I'm not a great programmer. I build an instrument that requires a computer interface, and I learned how to program at the time of writing the program, for most documentation work (which means I have re-written program one half package of time I learned new things like how to define data structures and so on).

    My question is about multithreading - in my application, I use the GUI to write a series of instructions, and then I press a "Start button" which loads the instructions on a Board that interprets and outputs some call digital logic by the precisely. In addition, if specified, the button 'start' begins a task DAQmx that takes a trigger of my Board and acquires data. As these scans can take a long time, it is better for me to run in a separate thread. I also try to run an additional thread that queries the Board of Directors for its status - if it is running, waiting for a trigger or stop - and updates a control LED to reflect the State periodically. The problem I have is that programming function, the Board of Directors and the audit of the State function has some overlap, which I imagine is the reason why I'm the General Protection faults.  I read on the Thread hangs and Thread-Safe queues, but those who seem to be especially on the transmission of data between threads. Ideally I would be able to make sure that two threads do not call the same function at the same time - how would implement this?

    In addition, I don't know if it is a problem of the two threads calling the same function at the same time (I dunno if it of a problem or not), or if the problem is the fact that when I call these functions, they need to access the USB interface and there may be some sort of conflict between them.  I'm really hitting a wall here because I think that I don't have a solid understanding of the operation of allocation memory and battery function.

    Hi Paul, from your description, it seems very likely that you have problems with contemporary access to the same resource from multiple threads, which could explain the GPF you receive.

    Thread locks are a common way to handle such situations, because they can allow a single thread to protect it from another thread any access to the shared resource.

    Locks are used is:

    1 create a lock before you need to use it (possibly at the start of the program)

    2. when a thread needs to access the USB port to communicate with the instrument, it must call CmtGetLock to block access from other threads: If the lock is free, it is acquired by the threads. If it is already owned by another thread, the thread waits on the CmtGetLock until the bolt is free

    3. once a lock is finished using the shared resource, it must call CmtReleaseLock to permitt the access to the resource from other threads

    4. at the end of the program, destroy the lock

    If you do not want to stay frozen in CmtGetLock of a thread there is a function in the library if the lock is free or not, so that you can stay in a loop waiting for the lock to be free, but with the wire still alive and able to continue its work (still without access to the shared resource (, of course).

    It is crucial that acquired locks are always released, otherwise the other threads will be permanently excluded from access to the shared resource: this review is particularly important when adding threads management, because you must be sure to release locks acquired even errors, when a policy of the commune is to jump to a label inside the error handling function and it is possible that a lock is held acquired errors.

  • Safe multithreading NI FPGA Interface C API?

    Hello

    I use the FPGA C API interface to communicate with the software labview on my FPGA OR. Some calls take a while to run, for example, reading on a FIFO so long timeout. So far, I assumed that the interface was not safe multithreading. It has now become annoying given the timeout problem described above. Try simply was not good, it can take a long time to create a "collison.

    Is the FPGA interface safe multithreading C API? Or, more specifically, the functions of FIFO reading can be called in parallel with read/write variables on the FPGA?

    Thank you.

    Hello MKAP,.

    It has been a while since I used the NI FPGA Interface C API, but it is what I remember and seem to be able to remember (and also found in the documentation):

    Functions related to the unloading and loading of the library are not thread-safe:

    http://zone.NI.com/reference/en-XX/help/372928D-01/CAPI/functions_required/

    On itself, this should be a problem:

    Your application should require that the NiFpga_Initialize is called before any other function associated with function calls NIFpga.

    In a similar way that unloading (NiFpga_Initialize) lof NiFpga brary should occur only when you are finished using it.

    With regard to multithreading, you must also keep in mind its mono-thread interrupts IRQ (if you plan to use them):

    http://zone.NI.com/reference/en-XX/help/372928D-01/CAPI/functions_interrupt/

  • Function calls multithreaded suddenly causing blockages

    I'm having a problem with function calls from multiple threads. There are two threads that everyone calls a function called save_program, including a DDCChannelHandleGroup and and a certain structure "show pulse" moved. The problem I have is that after that I called him save_program of one of the sons, it crashes when I try to call from the other thread. There are three contexts for this - two in the main thread and the other in the thread of data acquisition.

    If I call the save_program of one of the contexts in the main thread, the program crashes when I try to call it in the thread for the acquisition of data and vice versa. No problem since the two contexts in the same thread. I put a breakpoint in the function call and the first part of the executable code in save_program (declaration of variable initialized to NULL), and the program freezes between these two breakpoints. I checked and always executed entirely complete in each of the threads AND the call of CmtExitThreadPoolThread() also runs very well. I also locked up all instances of save_program in CmtGetLock/CmtReleaseLock calls without success. Oddly, these calls used to cause no problems with the exact configuration of multithreading even. I don't know what has changed.

    Hi PaulGanssle,

    It is very possible that you have already encountered a problem experienced in LabWindows/CVI where transactions must be completed before calling SaveFile.  I have included a link below that talks a little more about this problem.

    http://zone.NI.com/DevZone/CDA/tut/p/ID/12323#281013_by_Category

    It is a question that has been reported and is managed by R & D.  From now on, it is not a fix available but I hope we can find a work around that will work for your application.

    Please let me know if you have any other questions.

    Kind regards

    Kyle S

  • I am looking for use multithreading to run several tests in parallel on a single object to measure.

    I wait with multithreaded several tests in additional on an object to measure.  I looked in the main site and all the examples are in zip files which seems to me not being able to download successfully on the site.  Is someone there examples of files or whitepapers on the subject that I can consult?

    put a test in a sequence of void.  Then call this subsequence using New Thread as execution Options:

  • First time multithreading in Labview

    I learn Labview and this is my first project. I expect this behavior from my attached VI. I thought that both the indicator will increment asynchronously if I ask to wait for Member States inside the while loop. I thought indicator 1 will increment the thread will go to sleep to 1000ms and in the increase of the 2 indicator average time and he goes to sleep and so on. Please, need help in understanding multithreading with Labview.

    By plugging the output of the judgment of the upper loop of the lower loop, the lower loop is waiting for the top loop fill and send the value before it starts exectuing.  Try this:

  • Multithreading tcp connection

    Hello

    I build a labview server that communicates with a java client.

    The work of communication, but I have 2 problems:

    -Labview writes only the channel over tcp, so I threw Double chain, but when I try to read it reads a bad value. Anyone know what kind of flow, I can use in java?

    -How can I get a multithreaded server? After the first reading I have to wait for other events, that will happen during the execution of the program.
    I tried with two while loop with 2 tcp listening on different ports, but it did not work.

    Thanks for your help,
    Veronica


  • With the help of VISA Write in parallel loops (multithreading)

    Hello

    I got the idea to set up four parallel loops on a quad core with four EHR via serial port independently. I use the PXI-8430/8 and I was told that an independent operation of ports is possible.

    What I did was simply to put in place four parallel for loops consisting only of a single entry VISA. With the help of the Tools > profile > find parallelizable loops, they gave me the following warning

    This loop For may or may not be safe to parallelize. Warning (s):
    -A node in the loop For can have side effects.

    This means, that the pilot VISA screws are not suitable for multithreading? With the help of LV2010

    Thanks for your comments!

    See you soon

    Oli

    Here's some good reading on paralleled for loops.

    Regarding the caveat, it's just that - a warning. If you write commands on a device and orders must be received in the order then you cannot parallelize the loop. If the order does not matter then go ahead. But in the case of VISA wrote that a parallelized loop going not buy you anything. They are intended for operations of calculation intnesive.

    Just stick to four loops.

  • Why my reference FFT VI does not see gains multithreading?

    I am using a multicore processor to speed up the calculation of 32 FFT by running in four parallel threads, as shown in the code example below image. However, the difference in performance between single and multi-threading is only approx. 10% even on a Core 2 Quad CPU.

    I tried a few things, for example by placing the table split and merge functions or graphic waveform, outside the timed section, but this has very little effect - the main delay persists with screw FFT. These screws are already implemented reentrant, but somehow always do not perform well at the same time. Why?

    Can someone show a better performance gain in a similar VI? I'm using Labview 7.1, using pictures instead of a VI for the answers would be greatly appreciated!

    Thank you!

    Hello

    Thanks for your reply. In fact, I found the solution. Rather already internal multi-threading, the Express VI has done exactly the opposite, he broke internal capacity of multithreading, including several side bolts that were not reentrant. This means that the Global Spectral VI analysis Express is not reentrant and accelerate properly on a multi-core CPU.

    My solution was to dig in the Express VI until I found the most basic levels VI (DLL function calls etc.), which have been completely re-entrant. By extracting these and by simply registering this essential code as a new, fully environment sub - VI, I was able to unlock the potential full multi-core. My reference FFT VI runs now 5 times faster, simply by replacing the Express VI with the FFT VI stripped of myself.

    As a courtesy, I enclose my new, 5 x faster multi-core FFT VI.

    It evolves on an Intel Core 2 Quad CPU as follows:

    LabVIEW Spectral Analysis VI Express (single or multiple instances): 1 x speed

    Multi-Core FFT VI (single instance): 2.3 x 2.4 x Faster

    Multi-Core FFT VI (double instance): 3.7 x 4.0 x Faster

    Multi-Core FFT VI (quad instance): 4.8 x 6.1 x Faster

    Multi-Core FFT VI (instance octo): x 4.8 to 6.1 x Faster (could probably use a 8-core see benefits)

    Here are the internal features of the VI of FFT multi-core Lite:

Maybe you are looking for

  • Location Services does not-Macbook Pro and iPad 2

    I read through many questions is similar with location services. I recently moved from Shenyang in the northeast of China in Beihai in the South. The MacbookPro or my iPad can find my position. Before moving here, the two pieces of material worked we

  • Programmatically update nested arrays of Clusters? (What is the best way?)

    I have an array of configuration files that is loaded at startup. Then, I need to update the values in this table of configuration values. The attached VI works, but I was wondering if this is the best way. It seems not scalable I added elements that

  • get the values of the different acquisition channels

    Hello everyone, I finished my project and I want to do something and I did not how. I am acquising three signals from three different pressure sensons with the use of the DAQAssistant configuration to acquire form three analogue ports (there is a scr

  • ENVY dv6-7214nr: accidentally not removed controller network no internet

    Some time ago a friend of the family installed windows 7 I disliked windows 8, everything went pretty well except that he was never able to put my on my laptop ethernet controller. I tried to find the drivers and some how I managed to delete my netwo

  • HP Photosmart C7280: photos C7280 print sideways on the page

    When I print pictures from the iMac, they appear sideways on the page (oriented at 90 degrees on the short side of a 4 x 6 rather than the longest side).  I deleted and reinstalled the printer software.  "Flip horizontal" does not help.    Has starte