如何在Python中重用线程

2024-04-27 05:07:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把noPairs和noThreads作为用户的输入。例如,计算4 pairs using only 2 threads之间的最短路径。但在我的代码中,每对都会创建多个线程。相反,我想创建给定数量的线程,然后使用它们执行操作。有人能帮帮我吗。在

我的代码:

import threading
from py2neo import neo4j
from random import randint
#------------------------------------------------------------------------------ 

TOTAL = 0
MY_LOCK = threading.Lock()

class TestJVM(threading.Thread):

    def __init__(self,s_node,e_node):
        """
            Default constructor
        """
        self.graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
        self.query_string = """START beginning=node(%s), end=node(%s) 
                            MATCH p = shortestPath(beginning-[*]-end) 
                            RETURN p"""%(s_node,e_node)                     # Pass start and end node values
        threading.Thread.__init__(self)


    def run(self):
        """
            Run method
        """
        MY_LOCK.acquire()
        result = neo4j.CypherQuery(self.graph_db,self.query_string).execute()
        for r in result:
            print(r.p) # p is a py2neo.neo4j.Path object
        MY_LOCK.release()


if __name__ == "__main__":

    try:
        noThreads = int(input("Enter Number of Threads : "))
        noPairs = int(input("Enter Number of Pairs : "))                    # Take number of pairs as a input    
        for i in range(0,noPairs):        
            start_node = randint(0,20);                                     # Enter range for generating random numbers
            end_node = randint(0,20);                                       # Enter range for generating random numbers            
            print("start node is : %s and end node is : %s"%(start_node,end_node) )
            for t in range(0,noThreads):
                a = TestJVM(start_node,end_node)
                a.start()

    except Exception as e:
        print(e)

Tags: importselfnodeformyrangerandomstart