在main()的不同线程上调用2个函数时,只调用第一个函数

时间:2017-12-29 18:12:01

标签: python python-2.7

我正在尝试并行运行两个函数,所以我没有共享那个大代码,而是编写了一个更简单的版本,如下所示

import thread


def function1():
    print "in function 1"

def function2():
    print "in function 2"


# Create two threads as follows

def main():
    try:
       thread.start_new_thread( function1())
       thread.start_new_thread( function2())

    except Exception:
       print Exception.message

    while 1:
        pass


if __name__ == '__main__':
    main()

我得到以下输出

in function 1
<attribute 'message' of 'exceptions.BaseException' objects>

函数#2无效的任何原因

2 个答案:

答案 0 :(得分:1)

您需要在thread.start_new_thread电话中提出第二个参数。该函数的参数应作为元组传递。在你的情况下,这是一个空元组。

import thread

def function1():
    print "in function 1"

def function2():
    print "in function 2"

# Create two threads as follows

def main():

   thread.start_new_thread( function1, ())
   thread.start_new_thread( function2, ())


if __name__ == '__main__':
    main()

Python thread.start_new_thread documentation

答案 1 :(得分:0)

问题是start_new_thread需要至少2个参数,所以如果你的函数没有接受任何参数,那么传递它就像

 thread.start_new_thread( function_name,())

以下是工作代码

import thread


def function1():
    try:
        print "in function 1  \n"
    except Exception:
        print Exception.message

def function2():
    try:
        print "in function 2 \n"
    except Exception:
        print Exception.message


# Create two threads as follows

def main():

    try:
       thread.start_new_thread( function1,())
       thread.start_new_thread( function2 ,())
    except Exception:
        Exception.message

    while 1:
        pass



if __name__ == '__main__':
    main()