Adam
Adam

Reputation: 689

Python: Run a second function while first function is kept running

I want to Run 2 functions without waiting the first function to finish . I need to run a function "ListeningToReceive" to make port listening to receive data from remote agents, and while listening on that port, it executes the second function "RunRemoteAgents" to run remote agents in order to make them sending data to the listening port. I used threading, but it doesn't seem it is working, it just makes the port listening and doesn't execute the second function

#!/usr/bin/python
import threading

def ListeningToReceive():
        print "The port is open to receive data"
def RunRemoteAgensts():
        print "Running remote agents to send Data to the open port here"
if __name__ == "__main__":
        thread1 = threading.Thread(target=ListeningToReceive)
        thread2 = threading.Thread(target=RunRemoteAgents)
        thread1.start()
        thread2.start()

Upvotes: 1

Views: 2609

Answers (1)

Haifeng Zhang
Haifeng Zhang

Reputation: 31935

CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

Use multiprocessing instead:

from multiprocessing import Process
import time

def f(name):
    print 'hello', name
    time.sleep(10)
    print "f is done"

def f2():
    print "this is funct2"
if __name__ == '__main__':
    p1 = Process(target=f, args=('bob',))
    p2 = Process(target=f2, args=())

    processes = list()
    processes.append(p1)
    processes.append(p2)

    for p in processes:
        p.start()

Upvotes: 2

Related Questions