logo
down
shadow

Timeout child thread for python3


Timeout child thread for python3

By : Yazdan Ilyas
Date : November 23 2020, 03:01 PM
I wish this help you I gave up timing out the thread in my child thread.
So I used multi-process within the child thread to kill it. I could not find any other solution.
code :


Share : facebook icon twitter icon
Make parent thread wait till child thread completes or timeout

Make parent thread wait till child thread completes or timeout


By : Sergio Amed Alvarez
Date : March 29 2020, 07:55 AM
it helps some times YOu could do Thread.join(long) or Thread.join(long, int) and start process in separate thread.
Adding some code. (Works but Not fully tested with all corner cases)
code :
  public class Test {

     public static void main(String[] args) throws Throwable  {
        for(int i = 0; i < 3; i++) {
           ProcessRunner pr = new ProcessRunner(args);
           pr.start();
           // wait for 100 ms
           pr.join(100);
           // process still going on? kill it!
           if(!pr.isDone())  {
              System.err.println("Destroying process " + pr);
              pr.abort();
           }
        }
     }

     static class ProcessRunner extends Thread  {
        ProcessBuilder b;
        Process p;
        boolean done = false;

        ProcessRunner(String[] args)  {
           super("ProcessRunner " + args); // got lazy here :D
           b = new ProcessBuilder(args);
        }

        public void run()   {
           try   {
              p = b.start();

              // Do your buffered reader and readline stuff here

              // wait for the process to complete
              p.waitFor();
           }catch(Exception e) {
              System.err.println(e.getMessage());
           }finally {
              // some cleanup code
              done = true;
           }
        }

        int exitValue() throws IllegalStateException  {
           if(p != null)  {
              return p.exitValue();
           }         
           throw new IllegalStateException("Process not started yet");
        }

        boolean isDone()  {
           return done;
        }

        void abort()   {
           if(! isDone()) {
              // do some cleanup first
              p.destroy();
           }
        }
     }
  }
Does a Thread timeout or Thread.Sleep() for longtime close or abort a thread?

Does a Thread timeout or Thread.Sleep() for longtime close or abort a thread?


By : niks
Date : March 29 2020, 07:55 AM
wish helps you Instead of having a thread that sleeps for a long time. Make a short thread that sleeps a very short time (1 minute) and each time checks if enough time has passed since the last execution. This is much more robust and lets you track if your system is 'still alive'
Is it possible to suspend child thread then callback parent thread and then again resume child thread

Is it possible to suspend child thread then callback parent thread and then again resume child thread


By : ExcelledProducts
Date : March 29 2020, 07:55 AM
it should still fix some issue To get the desired output, you need not only pause the child thread when i == 5, but also need pause the main thread until the child thread print the first five abc.
You can use two CountDownLatch for communication between the child and main thread:
code :
import java.util.concurrent.CountDownLatch;

public class Main {


    static class Child implements Runnable {

        CountDownLatch waitLatch;
        CountDownLatch notifyLatch;

        public Child(CountDownLatch waitLatch, CountDownLatch notifyLatch) {
            this.waitLatch = waitLatch;
            this.notifyLatch = notifyLatch;
        }

        @Override
        public void run() {
            for (int i = 1; i <= 10; i++) {
                System.out.println("abc");
                if (i == 5) {
                    try {
                        notifyLatch.countDown(); // signal main thread, let it print number 5
                        waitLatch.await(); // wait for the signal from main thread
                    } catch (InterruptedException e) {

                    }
                }
            }
        }
    }

    public static void main(String[] args) {

        CountDownLatch waitLatch = new CountDownLatch(1);
        CountDownLatch notifyLatch = new CountDownLatch(1);

        Runnable child = new Child(waitLatch, notifyLatch);
        new Thread(child).start();

        try {
            notifyLatch.await(); // wait for the signal from child thread
        } catch (InterruptedException ignore) {

        }
        System.out.println(5);
        waitLatch.countDown(); // resume child thread
    }
}
Timeout in I/O function call in child thread

Timeout in I/O function call in child thread


By : LuCas Light
Date : March 29 2020, 07:55 AM
around this issue Better use Popen from the subprocess module. I also included the strategy from How to terminate a python subprocess launched with shell=True to fix issues with killing the process:
code :
import os
import signal
import subprocess
import time
from subprocess import PIPE, Popen

p = Popen("sleep 1; echo 1", shell=True, stdout=PIPE, preexec_fn=os.setsid)

WAIT = 0.5

started = time.time()

# do some other work for WAIT seconds:
while time.time() < started + WAIT:
    print("do something else")
    time.sleep(.1)

print("kill")

try:
    os.killpg(
        os.getpgid(p.pid), signal.SIGTERM
    )
except ProcessLookupError:
    # process possibly died already
    pass

print(p.stdout.read())
how child thread can notify parent thread to terminate all the other child thread java

how child thread can notify parent thread to terminate all the other child thread java


By : Prasad Madhushanka M
Date : March 29 2020, 07:55 AM
Any of those help That's not a sane way to do it. Just code the child threads to stop doing work that no longer needs to be done. Any time you catch yourself asking "How can I push my code around around from the outside to make it do with I want?", stop and correct yourself. The right question is, "How can I write my code to do what I actually want it to do in the first place so that I don't have to push it around from the outside?"
Related Posts Related Posts :
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org