Search code examples
pythonpython-3.xpython-multithreading

Is there a way to execute a file as a Thread using the threading module in python?


so I was wondering if it is possible to execute a file (wheather .py, .java or any other extensions) and display the output in the console.

Let's say that I have a main.py file and an file.java. Now if I would run the main.py, it would return You just runned the python file! in the console, and if I run the file.java file, it would return You just runned the Java file!

Now is it possible to create a third file, and usind the Threading module, execute both of the files at the same time and display the outputs live in the console of the new file?

I am sorry if this is a little weird. Thanks!


Solution

  • As mentioned in these answers (1, 2), CPython's GIL is unlikely to allow true parallelism with threading (which is useful for concurrency). The multiprocessing module is likely more effective for this, or alternatively using thread pools with a version of Python that does not implement the GIL such as JPython. Hope this helps.

    Here is an example using the multiprocessing module paracoded from 1, authored by user @NPE:

    from multiprocessing import Process
    import time
    
    
    def f1():
        print("f1: starting")
        time.sleep(100)
        print("f1: finishing")
    
    
    def f2():
        print("func2: starting")
        time.sleep(100)
        print("func2: finishing")
    
    
    if __name__ == "__main__":
        p1 = Process(target=f1)
        p1.start()
        p2 = Process(target=f2)
        p2.start()
        p1.join()
        p2.join()