Thread vs async timer in labwindows

i have a program in which i have to aquire / send data from serial port which is time critical ie 10 ms , my quension is that what are my options, can i use threads or use asynctimer (that can have 16 independent threads). i understand how to use asyncronus timer but my question is that are there anyother ways of creating threads in labwindows and are they as effective as asyncronous timer, please guide me in detail.
thanks in advance
regards ahsan

Well, async timers are an implementation of multithreading that rely on Windows multimedia timers for scheduling events; you may consider it as an application of multithreading. It's intended to give users an easy instrument to begin programming in multithreading without much effort: you can develop and debug your app using a UI timer and then switch it to async timer to execute it in a multithreaded environment without even changing the callback definition!
At the same time, this paradigm includes some constraints that may be not optimal in search for an optimized application.
Having said this, you must consider that maintaining a 10 ms regular pace with no-missing-codes requirement over a long time is *really* a difficult task, if not impossible on Windows: there are so many underlying tasks in this OS that you are never guaranteed that none of them will interrupt you at some moment. Trying to achieve this goal will imply a lot of work aimed to:
- make your app highly efficient
- tailor the OS to close or reduce time consuming activities that may interfere with your app (antivirus; automatic updates; scheduled tasks; unnecessary services; including some from NI...)
Frankly speaking, the 10ms constraint would claim for a real time environment, not for a Windows program!
Proud to use LW/CVI from 3.1 on.
My contributions to the Developer Zone Community
If I have helped you, why not giving me a kudos?

Similar Messages

  • Async timer stall behavior

    In service to my unending quest to understand async timers ...
    I have an app with two async timers, each with its own callback, and I understand both run on the same thread.
    So if one of the callbacks stalls, will the other ever get scheduled?  If they're truly on the same, single thread, then if you lock up one of the two callbacks (e.g. put it into an endless loop), then the other callback should never get called.
    Thanks.
    Solved!
    Go to Solution.

    Thanks for the info!
    Yes, I had seen behavior over long runs (application runs for weeks at a time, constantly using two async callbacks) that caused me to believe there was some unobvious semantic to the async timer scheduling, which you've just explained.  If this is NI implmentation detail, it's never been explained anywhere that I can find.
    I do need to prevent the 30 second callback from taking longer than the timer period - it normally doesn't, and in that case everything works as expected.
    I create the 15 second timer first, and that's the one that continues to get callbacks after the 30 sec timer stops getting its.
    What I still don't have a grip on, is that if it's the 15 second timer that gets priority, and it has enqueued a bunch of callbacks missed because the 30 second timer was stuck in it's callback, why doesn't the 15 second timer flush out all of it's enqueued callbacks once it's able to?  Otherwise, queueing them up doesn't make sense.  I would have thought that the 15 sec timer would flush it's enqueud callbacks out as fast as they were serviced, and then both timers would resume getting their callbacks per their schedules.
    Here's my code:
    #define POLL_INTERVAL 15
    #define CONTROL_INTERVAL 30
    // Create polling and control async timers, start callbacks
       iPollTimer    = NewAsyncTimer (POLL_INTERVAL, -1, 1, MeasurementPoll, 0);
       iControlTimer = NewAsyncTimer (CONTROL_INTERVAL, -1, 1, Control, 0);
    Another thought I have is that this is a fast, 8 core PC.  I wonder if there's some weirdness getting in due to the true parallel execution that can take place, though the async timers are on the same thread so shouldn't be a race there.
    When the 30 sec timer stops getting callbacks, the 15 sec timer callback interval gets stretched out to about 25 seconds - up until then, I see the expected, regular 15 and 30 sec callbacks.
    Thanks again.

  • Gui timer v/s Async timer priority

    Hi NI,
    I am trying to build an application where in i am communicating with an automotive ECU over RS-232 periodically. I am using an aysnc timer to do the communications part and a GUI timer to do the graphical object update. I have three questions for your team.
    1. What RTOS and PC configuration do you recommend for using a RT Async Timer with Prority ? (preferably whats available in the market today in terms of "cheap" hardware)
    2. What is the priority of the GUI timer when compared to the Async timer? Is is possible for the GUI timer to inetrrupt the Async timer fucntion call ? If yes...is there an exclusion mechanism that would stop this from happening ?
    3. I am using a two linked list concept...the first list populates while the other's data is being drawn on the strip chart...and then i flip over to populating the second linked list while the first lists data is being plotted. The communications(population of data in a structure in a linked list) is being done in the Async thread while the plotting is being done in the GUI thread. The issue i am facing is that i do not have a clean linked list population, plotting and freeing of data sequence...i feel this is due to some un-predictability in the timer function calls.(hence Q2 above). Do you recommend only using thread safe queues or do you think this is do-able with linked lists.
    Looking forward to your reponse.
    -Ashish

    I don't know what degree of certainity you need but a "fixed calling and execution sequence" is just a dream in a Windows environment.
    Windows will operate your threads together with many more of its own, all with varying priorities.
    So, you should think of priority as a vague way of making one thread to be operated more/less than another lower/higher degree thread.
    No thread priority class guarantees a certain frequency of thread execution.
    GUI timer callbacks are executed in the main program thread while async timers are executed in a seperate thread.
    So, yes their execution times may coincide. Hence the need to protect your global data.
    Data accessed by multiple threads should be protected so that, no thread would be interrupted in the middle of a write/read operation on that data.
    TSQs do that for you. Otherwise you cannot be sure about the integrity of the data you are plotting.
    If you need do some more reading about this. But TSQs stand out as a more elegant way to solve your problem.
    S. Eren BALCI
    www.aselsan.com.tr

  • M-Series read + Write, threading or async , performance issues

    I have a slightly unusual issue: Using 2 USB-6251 and 2 USB-6015 within the same application.
    1 of the USB-6251s reads data on a 50 msec look (Driven by an async timer).
    Depending on the input the code decides to output a 40 Hz, 300 usec  waveform  of varying amplitude  - the output goes one until there is  a user event that might make it stop.
    Now , here is the problem.  I have implemented the output function using a sepereate high priority thread and the delay( delay_in_sec) command.
    I find that while the data acquisition timer is NOT running the frequency of the output is very close to 40 Hz. When the data acquisition IS running , the frequency of the output varies considerably - most likely reflecting USB delays.
    I was able to see the output 40Hz, 300 usec waveform using a seperate app using a single async timer w/o any data acq and the timing was immaculate.
    My questions are:
    1. Could I use 2 different async timers in the same app - I tried to do this and the output was still wacky when I turned data acquisition on
    2. Is there any way outside the delay() command that could improve the timing accuracy of the analog output thread?
    3. I measured the time to create a 300 usec pulse of a certain amplitude, write it to the USB-6251 and start the task and it was ~ 13 msec. This is way too slow for 300 samples at 1 MHz - is it a USB bus limitation, or I should look at my design to see what is going on?
    4. Any NI hardware that would allow me to handle 4 analog outputs more gracefuly? (FYI, 2 of my outputs are at 1 MHz and 2 of them at 50 Hz).
    Thanks
    AP

    THanks for taking the time to look at my message.
    I am using 4 DAQs. First one, USB-6251 is used to collect data (4 analog inputs @ 20Hz) and also occasionally provide analog output @ 1 MHz.
    Second DAQ is a USB-6251 occasionally provide analog output @ 1 MHz.
    Third and Fourth DAQ  areUSB-6015 occasionally providing analog output @ 50 Hz.
    All devices are connected via USB to a Dell Dual Core notebook.
    THis is how I create & configure the analog output channels - using 1 task per device.
                        DAQmxErrChk(DAQmxCreateAOVoltageChan(TaskAnalogX,channelstring , "Ramp 1",0 , 10, DAQmx_Val_Volts, ""));
                        DAQmxErrChk(DAQmxCfgSampClkTiming(TaskAnalogX, "",1MHz OR 50Hz, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps     , SECONDS*1MHz));
                        DAQmxErrChk(DAQmxWriteAnalogF64 (TaskAnalog1, ( int32 )SECONDS*1MHz OR 50Hz ), 0, DAQmx_Val_WaitInfinitely, DAQmx_Val_GroupByChannel , PHAOarr, &sampsPerChanWritten, NULL));
    THe design/architecture is pretty complex but on a very high level whenever I need to deliver analog output I configure the output waveforms and then write it to the DAQs and then use some timers/logic to deliver the waveform from the DAQ as needed.
    Now the challenge has been that in one specific case I need to deliver analog output of uknown duration (whereas everything else is deterministic). In that case i  created a seperate thread and write each 300 usec pulse individually to the analog output (using USB 6251)using the following tASK:
                        DAQmxErrChk(DAQmxCreateTask("Tonic Output Task", &TaskTonic));  
                        DAQmxErrChk(DAQmxCreateAOVoltageChan(TaskTonic, channelstring , "PulseToPulse",0 , 10, DAQmx_Val_Volts, ""));    
                        DAQmxErrChk(DAQmxCfgSampClkTiming(TaskTonic, "",1.0E+06, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps , 301));
    As described in my first message this is very sensitive to timing and it takes 13 msec to stop the task , write the array to the DAQcard and then start the task again.
    On the hardware timing recommendation. I tried to configure the DAQ  using the DAQmx_Val_HWTimedSinglePoint samplemode but it seems not to be supported by the hardware I am using.  Is there a CVI example of using hardware timing that I can take a look at?
    THanks
    AP
    Hi AP,
    My first impression is that you would want to use hardware timing
    rather than software timing.  Try using a DAQmx Timing command and
    specify the rate there.  Aside from that, could you be more specific
    about your application?  How do you have your hardware set up and which
    devices are handling each part of the task?  How are you generating the
    output?
    Regards,
    Joe S.

  • How to enable EDT to interrupt the worker thread at any time?

    Hello, this is a Swing application - in order for EDT to be responsive, I do the graphical computation in another thread. The computation is very CPU intensive, and I notice the controls are a little jerky - that means the EDT can't get to event handling as fast as I would like. If I do a sleep in the computation thread, instead of work, then controls are smooth as silk - this proves to me that I am doing it right, it's just that the computation is hogging up the CPU. The initial priorities of both EDT and the computation thread are the same (4) - I tried to change the comp thread priority to minimal (1), with success. But even with the higher priority, EDT is still jerky. I even tried (I know gurus are gonna slap me for that) to change the priority of the EDT to max (10), from within the EDT, that was not successfull, the priority stayed at 4, but did not throw SecurityException.
    Anyway, how do I set it up, so that EDT can interrupt my thread, at any time, so EDT never has to wait for CPU?
    Mark

    But then I asked myself - then why, when I leave the computation thread sleeping, and still do "a little bit" of computation in EDT, it is smooth...
    the answer is quite amazing (at least to me, a newbie) - if the comp thread is not doing anything, the result is "simple" and ...
    it turns out, that if the thing that you are drawing, like a series of drawLine() calls, many of them, if the result is simple, like they together form a one long line, then Swing appears to do it faster, than if they do not form anything that can be simplified. It appears, that Swing merges your draw... calls as much as possible to actually make as few drawing calls as possible.

  • How to start two threads at a time

    hi to all,
    can any one tell me how we can start two or more threads at a time
    this is my req in the application i want to check that
    can any body help me in this regard.
    ashok

    If you are starting a whole bunch of threads, and want them to be eligable for execution at about the same time (i.e. dont get staggered due to the overhead of starting), then you can use locking / waiting.
    I've not really had / wanted to do this before, but I suppose something like the following might work:
    import EDU.oswego.cs.dl.util.concurrent.Latch;
    import EDU.oswego.cs.dl.util.concurrent.Sync;
    public class StartupTest {
      private void test() {
        Latch startGun = new Latch();
        // create and start some threads - I'll just create one
        Thread t = new Thread(new TestRunnable(startGun));
        t.start();
        // all started? Ok - fire the start gun to release them
        startGun.release();
      private class TestRunnable implements Runnable {
        private Sync startGun;
        TestRunnable(Sync startGun) {
          this.startGun = startGun;
        public void run() {
          waitForStart();
          // what ever you were going to do here......
        private void waitForStart() {
          try {
            startGun.acquire();
          } catch (InterruptedException e) {
            // what ever... I'll just bharf.
            throw new RuntimeException(e);
    }Even with this, your threads aren't going to actually start working all at exactly the same time - but they'll all be eligable to start working at the same time.

  • What is Thread Safety in timer jobs on SharePoint?

    Hi All,
    What is Thread Safety in timer jobs on SharePoint?
    Thanks in advance!

    hi
    thread safety in timer jobs means the same as in other code: it should be possible to run multiple instances of the same job simultaneously. If job uses some shared resource, access to this resource should be synchronized. But the tricky moment is that it
    is not enough to just use standard .Net thread synchronization mechanisms here (e.g. lock), because in most cases Sharepoint runs on the server farm and the same job instance may be executed on different servers while standard synchronization mechanisms work
    within single process memory space (it is possible to guarantee that jobs are running on the same server by assigning preferrable server for timer jobs in Central administration > Content databases > content database, but often it is left to Sharepoint
    to decide on what server jobs are executed). In case of timer jobs you need to store some flag that job is started in some shared storage, e.g. in SPWebApplication.Properties:
    lock(obj)
    try
    if ((bool)web.AllProperties["jobstarted"])
    return;
    web.SetProperty("jobstarted", true);
    web.Update();
    finally
    web.AllProperties.Remove("jobstarted");
    web.Update();
    It is just idea and there is still minor possibility that 2 jobs instances may run at the same time (if 2nd job instances set jobstarted flar after 1st jobs checked it in AllProperties, but before 1st jobs set it), but it will solve most of the problems in
    reality. In order to make the code more secure you may use timestamps instead of flag.
    Blog - http://sadomovalex.blogspot.com
    Dynamic CAML queries via C# - http://camlex.codeplex.com

  • Async timer slows operation down

    Having previously used asynchronous timers to resolve another problem that I had, I'm now looking at an issue that has got me stumped
    Here is a code snippet which has had an asynchronous timer applied
    int CVICALLBACK ParentEvent (int reserved, int control, int event, void *callbackData, int eventData1, int eventData2)
    static int iInfoFlag = 1;
    //If Com Timer event has occurred then:
    if (event == EVENT_TIMER_TICK)
    SetAsyncTimerAttribute(control,ASYNC_ATTR_ENABLED, 0);
    //First, has sonde configuration changed?
    if (iSondeConfigure_HasChanged() == YES)
    //Re-initialise displays etc, if true
    InitialiseSondeSystems(iFloatingPanels);
    //Get Sonde data
    if (ProgStatus.bComTimerEvent == TRUE)
    CompactDataControl (hParentPanel, iInfoFlag, &ProgStatus, NULL);
    //If Com events are disabled then set Sonde Info flag for next data
    //acquisition sequence
    if (ProgStatus.iComEnable != ENABLED)
    iInfoFlag = 1;
    SetAsyncTimerAttribute(ParentTimer,ASYNC_ATTR_ENABLED, 1);
    return(0);
    This routine was previously handled by a conventional timer but as these sit at the bottom of the pile when it comes to scheduling, as soon as the interface was manipluated it shut up. The timer in each case is set at 0.1 second, and if the bComTimerEvent flag is set to true, which is controlled by another (currently traditional timer) it goes away and grabs data from an external source. Using traditional timers, I can clock this 'grab the data' timer quite happily at 0.25 seconds. However with the code shown, it wont grab data any faster than about 1.5 seconds. I have timed how long it takes to call and return from CompactDataControl. With traditional timers its about 0.2 seconds, with the code as shown, its about 1.45 seconds.
    Any thoughts as to what I've missed or messed up.
    Regards
    Gavin
    Solved!
    Go to Solution.

    All I'm doing is calling Timer() before and after a particular function, and working out how long it takes... I've done this with both normal, and async callbacks and got significant differences. I think due to the nature of what has been done already, this code will need the same treatment as the last project I worked on that required async timers, which was a complete rewrite from the ground up. What is interesting is that that project does make changes to the GUI based on the async timers, without any obvious performance issues, despite of the fact that elements of the GUI are created in the main thread. However this project is doing an awful lot more, which might in someway explain this.
    I'd be interested to know if there is any way you can use traditional timers without the problems of timers stopping, when moving or resizing the GUI - the thing I am try to prevent by using async timers
    However I think what youre saying about your use of Async timers for number crunching, and standard timers for GUI update is a good idea, and I'm pretty sure would work for me.

  • How can I use the same thread to display time in both JPanel & status bar

    Hi everyone!
    I'd like to ask for some assistance regarding the use of threads. I currently have an application that displays the current time, date & day on three separate JLabels on a JPanel by means of a thread class that I created and it's working fine.
    I wonder how would I be able to use the same thread in displaying the current time, date & day in the status bar of my JFrame. I'd like to be able to display the date & time in the JPanel and JFrame synchronously. I am developing my application in Netbeans 4.1 so I was able to add a status bar in just a few clicks and codes.
    I hope somebody would be able to help me on this one. A simple sample code would be greatly appreciated.
    Thanks in advance!

    As you're using Swing, using threads directly just for this kind of purpose would be silly. You might as well use javax.swing.Timer, which has done a lot of the work for you already.
    You would do it something like this...
        ActionListener timerUpdater = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // DateFormat would be better, but this is an example.
                String timeString = new Date().toString();
                statusBar.setText(timeString);
                someOtherLabel.setText(timeString);
        new Timer(1000, timerUpdater).start();That code will update the time once a second. If you aren't going to display seconds, you might as well increase the delay.
    The advantage of using a timer over using an explicit thread, is that multiple Swing timers will share a single thread. This way you don't blow out your thread count. :-)

  • Kernel task is hogging lots of threads and CPU time

    My Mavericks Quad Macbook Pro is getting pretty slow these days and at some point I'll have to reinstall everything I think. However I can't start that for a while as I have important projects on the go. I looked in Activity Monitor first and I can see a kernel task constantly running with no indication of what it is doing. So I opened Console and looked at the Diagnostic log. I can see a lot of lines referring to com.apple.message. Hundreds of identical lines actually. I did not have Messages running so I opened it, and sure enough that showed up in console live. However the log shows a slightly different app and a totally different UUID, which seems odd.
    Anybody understand what this is all about? See below. I opened one of the endlessly repeating items plus one that I know is from the Messages app below it.
    23/03/2015 08:28:29.242 UserEventAgent[235]: com.apple.message.domain: com.apple.usage.app_activetime
    com.apple.message.signature: universalAccessAuthWarn
    com.apple.message.signature2: com.apple.accessibility.universalAccessAuthWarn ||| 1.0 (190.1)
    com.apple.message.value: 633
    com.apple.message.value2: 0
    com.apple.message.value3: 0
    com.apple.message.value4: 0
    com.apple.message.value5: 0
    com.apple.message.value6: 0
    com.apple.message.value7: 0
    com.apple.message.result: NO
    com.apple.message.summarize: YES
    Sender_Mach_UUID: 55428B1C-9198-32BF-80EA-4731081F402E
    23/03/2015 08:44:17.426 Messages[8722]: com.apple.message.domain: com.apple.iChat.app.weeklyStats
    com.apple.message.video_chat_passed: 0
    com.apple.message.video_chat_failed: 0
    com.apple.message.video_chat_noop: 0
    com.apple.message.audio_chat_passed: 0
    com.apple.message.audio_chat_failed: 0
    com.apple.message.audio_chat_noop: 0
    com.apple.message.screen_sharing_passed: 0
    com.apple.message.screen_sharing_failed: 0
    com.apple.message.screen_sharing_noop: 0
    com.apple.message.average_message_length: 0.000000
    com.apple.message.messages_sent: 0
    com.apple.message.messages_received: 0
    com.apple.message.sms_sent: 0
    com.apple.message.sms_menu_used: User never selected SMS menu
    com.apple.message.result: pass
    com.apple.message.imessage_offered_upgrades: 0
    com.apple.message.imessage_upgrades: 0
    com.apple.message.imessage_declines: 0
    com.apple.message.imessages_sent: 0
    com.apple.message.imessages_received: 0
    Sender_Mach_UUID: 212E34A8-B310-3729-8D11-879E9985A0BD
    23/03/2015 08:44:17.427 Messages[8722]: com.apple.message.domain: com.apple.iChat.app.servicesUsedThisWeek
    com.apple.message.aim: 0
    com.apple.message.bonjour: 0
    com.apple.message.yahoo: 0
    com.apple.message.jabber: 0
    com.apple.message.google_talk: 0
    com.apple.message.imessage: 1
    com.apple.message.other: 0
    com.apple.message.result: pass
    Sender_Mach_UUID: 212E34A8-B310-3729-8D11-879E9985A0BD
    23/03/2015 08:44:32.607 Messages[8722]: com.apple.message.domain: com.apple.iChat.app.prefs
    com.apple.message.one_on_one_style: com.apple.iChat.Styles.Balloons-ShowPictures
    com.apple.message.group_style: com.apple.iChat.Styles.Balloons-ShowPictures
    com.apple.message.incoming_bg_color: Automatic
    com.apple.message.outgoing_bg_color: Automatic
    com.apple.message.incoming_font: Default 12.000000
    com.apple.message.outgoing_font: Default 12.000000
    com.apple.message.save_history: Don't Save
    Sender_Mach_UUID: 212E34A8-B310-3729-8D11-879E9985A0BD

    The kernel_task is the heart of the operating system.  It will have on the order of a 100 threads (more or less).  So when you ask the operating system to do something, like read/write a disk, do network I/O, talk to your mouse/trackpad, keyboard, monitor, etc... kernel_task is the code that is going to do that at the lowest levels.
    Also if you have installed any 3rd party drivers (kernel extensions), they are going to become part of kernel_task and the CPU time they use will be part of kernel_task.
    If you have anti-malware, Mac cleaner or memory cleaner software installed, many of these packages install drivers that then try to out-guess the kernel_task and often result in slowing down the system, interfering with the normal operation of the system, or causing kernel panics.  These kinds of packages are not recommended by long term forum contributors.
    Please provide the output from EtreCheck, which will show the 3rd party additions you have installed.
    <https://discussions.apple.com/docs/DOC-6174>

  • How to run a thread for second time ?

    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();

    baskark wrote:
    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();
    It's usually helpful to check the documentation:
    [http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()|http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()]
    start
    public void start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
    So, make a new java.lang.Thread

  • DBMS_PARALLEL_EXECUTE multiple threads taking more time than single thread

    I am trying to insert 10 million records from source table to target table.
    Number of chunks = 100
    There are two scenarios:
    dbms_parallel_execute(..... parallel_level => 1) -- for single thread
    dbms_parallel_execute(..... parallel_level => 10) -- for 10 threads
    I observe that the average time taken by 10 threads to process each chunk is 10 times the average time taken in case of single thread.
    Ideally it should be same which would reduce the time taken by a factor of 10 (due to 10 threads).
    Due to the above mentioned behavior, the time taken is the same in both cases.
    It would be great if anybody can explain me the reason behind such behavior.
    Thanks in advance

    Source Table = TEST_SOURCE
    Target Table = TEST_TARGET
    Both tables have 100 columns
    Below is the code:
    DECLARE
    l_task VARCHAR2(30) := 'test_task_F';
    l_sql_stmt VARCHAR2(32767);
    l_try NUMBER;
    l_stmt VARCHAR2(32767);
    l_status NUMBER;
    BEGIN
    l_stmt := 'select dbms_rowid.rowid_create( 1, data_object_id, lo_fno, lo_block, 0 ) min_rid,
                                       dbms_rowid.rowid_create( 1, data_object_id, hi_fno, hi_block, 10000 ) max_rid
                                       from (
                                       select distinct grp,
                                  first_value(relative_fno)
                                  over (partition by grp order by relative_fno, block_id
                                  rows between unbounded preceding and unbounded following) lo_fno,
                                  first_value(block_id )
                                  over (partition by grp order by relative_fno, block_id
                                  rows between unbounded preceding and unbounded following) lo_block,
                                  last_value(relative_fno)
                                  over (partition by grp order by relative_fno, block_id
                                  rows between unbounded preceding and unbounded following) hi_fno,
                                  last_value(block_id+blocks-1)
                                  over (partition by grp order by relative_fno, block_id
                                  rows between unbounded preceding and unbounded following) hi_block,
                                  sum(blocks) over (partition by grp) sum_blocks
                                  from (
                                  select relative_fno,
                                  block_id,
                                  blocks,
                                  trunc( (sum(blocks) over (order by relative_fno, block_id)-0.01) / (sum(blocks) over ()/100) ) grp
                                  from dba_extents
                                  where segment_name = upper(''TEST_REGION_SOURCE'')
                                  and owner = ''FUSION'' order by block_id
                             (select data_object_id from user_objects where object_name = upper(''TEST_REGION_SOURCE'') )';
    DBMS_PARALLEL_EXECUTE.create_task (task_name => l_task);
    DBMS_PARALLEL_EXECUTE.create_chunks_by_sql(task_name => l_task,
    sql_stmt => l_stmt,
    by_rowid => true);
    l_sql_stmt := 'insert into FUSION.TEST_REGION_TARGET(REGION_ID,REGION1,REGION2,REGION3,REGION4,
                             ...., REGION99
                             SELECT REGION_ID,REGION1,REGION2,REGION3,REGION4,
                             .....,REGION99
                             from FUSION.TEST_REGION_SOURCE WHERE (1=1) AND rowid BETWEEN :start_id AND :end_id ';
    DBMS_PARALLEL_EXECUTE.run_task(task_name => l_task,
    sql_stmt => l_sql_stmt,
    language_flag => DBMS_SQL.NATIVE,
    parallel_level => 10);
    -- If there is error, RESUME it for at most 2 times.
    l_try := 0;
    l_status := DBMS_PARALLEL_EXECUTE.task_status(l_task);
    WHILE(l_try < 2 and l_status != DBMS_PARALLEL_EXECUTE.FINISHED)
    Loop
    l_try := l_try + 1;
    DBMS_PARALLEL_EXECUTE.resume_task(l_task);
    l_status := DBMS_PARALLEL_EXECUTE.task_status(l_task);
    END LOOP;
    DBMS_PARALLEL_EXECUTE.drop_task(l_task);
    END;
    Edited by: 943978 on Jul 2, 2012 9:22 AM

  • Thread pool with AT MOST one thread at a time

    Hi,
    I want to create a pool that creates at most one thread when it is needed. I want the pool to terminate the thread when it is idle for some time. Executors.newSingleThreadExecutor() creates a thread pool with one thread, but this thread doesn't die if idle...
    The code below also doesn't work - no thread is ever created:
    new ThreadPoolExecutor(0, 1, 30, TimeUnit.SECONDS,
                              new LinkedBlockingQueue<Runnable>());Thanks in advance

    Use Future.get().
    package net.jcip.examples;
    import java.util.concurrent.*;
    import static java.util.concurrent.TimeUnit.NANOSECONDS;
    * RenderWithTimeBudget
    * Fetching an advertisement with a time budget
    * @author Brian Goetz and Tim Peierls
    public class RenderWithTimeBudget {
        private static final Ad DEFAULT_AD = new Ad();
        private static final long TIME_BUDGET = 1000;
        private static final ExecutorService exec = Executors.newCachedThreadPool();
        Page renderPageWithAd() throws InterruptedException {
            long endNanos = System.nanoTime() + TIME_BUDGET;
            Future<Ad> f = exec.submit(new FetchAdTask());
            // Render the page while waiting for the ad
            Page page = renderPageBody();
            Ad ad;
            try {
                // Only wait for the remaining time budget
                long timeLeft = endNanos - System.nanoTime();
                ad = f.get(timeLeft, NANOSECONDS);
            } catch (ExecutionException e) {
                ad = DEFAULT_AD;
            } catch (TimeoutException e) {
                ad = DEFAULT_AD;
                f.cancel(true);
            page.setAd(ad);
            return page;
        Page renderPageBody() { return new Page(); }
        static class Ad {
        static class Page {
            public void setAd(Ad ad) { }
        static class FetchAdTask implements Callable<Ad> {
            public Ad call() {
                return new Ad();
    }

  • Stopping a thread after a time

    Hi,
    I'd like to be able to run a thread for a certain time and, based on it's state, then either run it for a longer time or suspend it. It'd be a bit awkward to do this in the thread itself, so I was thinking it'd be best to have another timer thread that interrupted it after n seconds. Unfortunately I'm not sure how to do this, despite a lot of searching.
    Cheers,

    You could try something like this ...
    public class ThreadToThread {
      public static void main(String[] argv) {
        ThreadToThread ttt = new ThreadToThread();
        TempThread tt = ttt.new TempThread();
        tt.start();
        for (int i = 1; i < 11; i++) {
          try {
            Thread.sleep(5000);
            System.out.println("loop #"+i);
            if (tt.isDone())
              break;
          catch(InterruptedException ie) {
            System.out.println("In main: "+ie);
        if (!tt.isDone())
          tt.setDone();
        System.out.println("Done");
      class TempThread  extends Thread {
        boolean done;
        long    l;
        public void run() {
          while ( !done ) {
            doSomething();
        private void doSomething() {
          long   i = 0;
          double j = 0;
          System.out.println("In doSomething ... starting calculations ... ");
          for (; i < 50000000L; i++) {
            j = ((((j / 2.005) * .0075) % 10000.25) * Math.random()*10 * Math.sqrt(i));
          done = true;
          System.out.println("In TempThread ... done!");
        private boolean isDone() {
          return( done );
        private void setDone() {
          System.out.println("Setting done to true");
          done = true;
    }

  • Threads in real time games

    For a game like Starcraft or Diablo 2 (or any real time game) is it standard practice to make a seperate thread for each object (such a monsters / units, etc.)
    Thanks.

    no, the overhead would become to great. There is one "master thread" for all monsters, which will keep track of their state, possibly one thread for each player in the case of RTS games like Starcraft. The game engine will have all kinds of tricks to make the AI seem smart, while they are actually pretty dumb and take up little cpu power. A single thread can keep track of hundreds of units this way.

Maybe you are looking for