python threading令人困惑的代码' int'对象不可调用

时间:2014-09-08 23:27:19

标签: python mysql multithreading

我知道它凌乱,但线程是如此令人困惑...我不知道问题是在我的sintax中,还是在我使用的方法中... def在mysql中插入(并且它在没有线程时工作),另一个奇怪的事情是在运行代码之后我注意到行正确插入但我仍然得到" self._target(* self._args,** self._kwargs) TypeError:' int'对象不可调用"

def thistaginsert(tagy):
    global idn
    global forbidentags
    global termcount
    tagy = tagy[0]
    if not tagy.isdigit():
        if not tagy in forbidentags:
            wordpress.execute(s_term % tagy)
            term0 = wordpress.fetchall()
            term0 = term0[0][0]
            if term0 == 0:
                tmp_i_term = i_term.format(tag1=tagy, tag2=tagy)
                wordpress.execute(tmp_i_term)
                cnx2.commit()
                tmp_s_termname = s_termname.format(buceta=tagy)
                wordpress.execute(tmp_s_termname)
                term = wordpress.fetchall()
                term = term[0]
                wordpress.execute(i_termtax % term)
                cnx2.commit()
                wordpress.execute(s_tax % term)
                tax_id = wordpress.fetchall()
                tax_id = tax_id[0][0]
                tmp_i_RL = i_RL.format(idn=idn, taxid=tax_id)
                wordpress.execute(tmp_i_RL)
                cnx2.commit()
                termcount += 1
            else:
                tmp_s_termname = s_termname.format(buceta=tagy)
                wordpress.execute(tmp_s_termname)
                term = wordpress.fetchall()
                term = term[0]
                wordpress.execute(s_tax % term)
                tax_id = wordpress.fetchall()
                tax_id = tax_id[0][0]
                tmp_i_RL = i_RL.format(idn=idn, taxid=tax_id)
                wordpress.execute(tmp_i_RL)
                cnx2.commit()
                termcount += 1
        return termcount
.
.
. #many lines later
                if tags:
                  for tag in tags:
                        ttt = Thread(target=thistaginsert(tag))
                        ttt.start()
                        threads.append(ttt)
                else:
                    print('no tags')

1 个答案:

答案 0 :(得分:2)

您正在直接调用该函数,然后将结果作为目标函数传递给Thread()构造函数。由于函数返回一个int,这解释了错误;您正在尝试使用int作为线程的入口点,并且int不可调用。

据推测,您打算让函数调用发生在另一个线程上。要做到这一点,请更改:

ttt = Thread(target=thistaginsert(tag))
#                   ^
# This invokes the function and uses the result as the "target" argument.

要:

ttt = Thread(target=lambda: thistaginsert(tag))
#                   ^
# This syntax creates a new function object that will call thistaginsert(tag) when
# it is called, and that new function is what gets passed as the "target" argument.

正如评论中所指出的,你也可以这样做:

ttt = Thread(target=thistaginsert, args=(tag,))
#                               ^ Note the lack of parens; we are passing the
#                                 function object, not calling it!