触发另一个函数,直到它首先在

2024-04-18 22:41:30 发布

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

我在stackoverflowgoogle中搜索了这么多的解决方案,却没有找到解决我问题的方法。我知道有很多这样的问题,但我没有从这些问题中找到任何解决方案。你知道吗

我的问题是:

我正在用python编写一个脚本,它将使用threading模块调用两个不同的函数。我需要调用第二个函数,直到第一个函数完成,因为我正在下载第一个函数中的数据,并且必须在第二个函数中使用相同的数据。我将数据以列表的形式存储在一个文件中。你知道吗

调用函数的脚本:

def trigger_fiftyusers():
    try:
        for k in range(50):

            # calling first function
            syncUpFun = threading.Thread(target=func1)
            syncUpFun.start()
            syncUpFun.join()

            # calling second function
            syncDownFun = threading.Thread(target=func2)
            syncDownFun.start()
            syncDownFun.join()
except Exception as error:
    print(error)
    print(traceback.format_exc())

例如:

我的第一个功能是:

def func1():
    list1=[]
    print "func1"
    # some code here
    list1.append("some data")
    return list1

我的第二个功能是:

def func2():
    print "func2"
    # some code here for getting the data from func1
    return list1

输出应为:

func1
func1
func1
func1

func2
func2
func2
func2

我在ubuntu16.04中使用python2.7.12


Tags: 数据函数脚本fordefsome解决方案print
2条回答

我修改了func1,尝试一下这个修改,我想它会按照你的想法执行。你知道吗

def func1():
 list1=[]
 print "func1"
 # some code here
 list1.append("some data")
 syncDownFun = threading.Thread(target=func2)
 syncDownFun.start()
 syncDownFun.join()
 return list1

尝试包装func1和func2调用,例如:

def trigger_fiftyusers():

    def _wrapper():
        func1()
        func2()

    #Send them all
    threads = []
    for k in range(50):
        t = threading.Thread(target=_wrapper)
        t.start()
        threads.append(t)

    #Wait for all of them
    for t in threads:
        t.join()

相关问题 更多 >