0

我的问题交织在我的代码中:

#!/usr/bin/python

import threading
import logging, logging.handlers
import hpclib
import json
import time
from datetime import datetime
from features import *
import sys


if len(sys.argv) != 3:
    print "Please provide the correct inputs"
        print "Usage: rest_test.py <controllerip> <counter>"
    sys.exit()


controller = sys.argv[1]
counter = int(sys.argv[2])



class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

def datapath_thread(ipaddress, testlogfile,count):
    #initialize logging system
    testlogger = logging.getLogger("testlogger")
    testlogger.setLevel(logging.DEBUG)
    file = open(testlogfile,'w')
    file.close()
    # This handler writes everything to a file.
    h1 = logging.FileHandler(testlogfile)
    f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
    h1.setFormatter(f)
    h1.setLevel(logging.DEBUG)
    testlogger.addHandler(h1)
    mylib = hpclib.hpclib(ipaddress)
    success_count = 0
    failure_count = 0
    for i in range(count):
        t1=datetime.now()
        try:
            (code, val) = datapaths.listDatapaths(mylib)

我想将此函数datapaths.listDatapaths(mylib)作为参数从下面的线程传递,例如(code,val)=functionname

            if code == 200:
                success_count +=1
            else:
                testlogger.debug("Return Code other than 200 received with code = %d, value = %s"%(code,val))
                failure_count +=1
        except:
            failure_count += 1
            testlogger.debug ("Unexpected error: %s"%sys.exc_info()[0])
            continue

        t2=datetime.now()
        diff=t2-t1
        testlogger.debug('RETURN code: %d. Time taken in sec = %s,Iteration = %d, Success = %d, Failure = %d'%(code,diff.seconds,i+1,success_count,failure_count))
        time.sleep(1)

    testlogger.removeHandler(h1)

# Passing ipadress of controller and log file name
t1 = FuncThread(datapath_thread, controller, "datapaths.log",counter)

在这里,我想将函数名称作为参数之一传递,例如t1 = FuncThread(datapath_thread, controller, datapaths.listDatapaths(mylib),"datapaths.log",counter)

t1.start()
t1.join()

我有很多这样的函数要调用,所以想要一种简单的方法来使用多个线程从一个函数调用所有函数

4

1 回答 1

2

首先,FuncThread不是很有用 -FuncThread(func, *args)可以拼写为Thread(target=lambda: func(*args))or Thread(target=func, args=args)

你已经很接近了 - 不是传入调用函数的结果,而是传入函数本身

def datapath_thread(ipaddress, test_func, testlogfile, count):
    # ...
    for i in range(count):
        # ...
        try:
            (code, val) = test_func(mylib)
        #...
thread = Thread(target=datapath_thread, args=(
    controller,
    datapaths.listDatapaths,
    "datapaths.log",
    counter
))
于 2013-09-16T19:37:55.393 回答