Python并发性-t1.start()类型错误:';int';对象不可调用

Python并发性-t1.start()类型错误:';int';对象不可调用,python,multithreading,concurrency,multiprocessing,Python,Multithreading,Concurrency,Multiprocessing,我最近在一次技术采访中得到了这个问题: 打印系列010203040506。使用多线程,第一个线程只打印0,第二个线程只打印偶数,第三个线程只打印奇数。 虽然我在Python方面有一些经验,但我从未真正编写过任何多线程代码。所以在阅读了一些文档之后,我成功地创建了一个类来完成这项工作。我正试着把事情放在一起,但不知道该怎么做。有人能帮我提供一个基于锁或信号量的解决方案吗 import threading class PrintSeries(threading.Thread): de

我最近在一次技术采访中得到了这个问题:

打印系列010203040506。使用多线程,第一个线程只打印0,第二个线程只打印偶数,第三个线程只打印奇数。

虽然我在Python方面有一些经验,但我从未真正编写过任何多线程代码。所以在阅读了一些文档之后,我成功地创建了一个类来完成这项工作。我正试着把事情放在一起,但不知道该怎么做。有人能帮我提供一个基于锁或信号量的解决方案吗

  import threading


class PrintSeries(threading.Thread):
    def __init__(self, start, stop, step, string):
        threading.Thread.__init__(self)
        self.string = string
        self.start = start
        self.stop = stop
        self.step = step

    def run(self):
        if self.start < self.stop:
            self.start += self.step
        self.string += str(self.start)
s = ''
t1 = PrintSeries(0, 0, 0, s)
t2 = PrintSeries(1, 2, 5, s)
t3 = PrintSeries(2, 2, 6, s)

t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
print(s)
导入线程
类PrintSeries(threading.Thread):
定义初始化(自、开始、停止、步骤、字符串):
threading.Thread.\uuuuu init\uuuuuu(自)
self.string=string
self.start=开始
self.stop=停止
self.step=step
def运行(自):
如果自启动<自停止:
self.start+=self.step
self.string+=str(self.start)
s=“”
t1=打印系列(0,0,0,s)
t2=打印系列(1,2,5,s)
t3=打印系列(2,2,6,s)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
印刷品
在任何情况下,即使这样也会出现以下错误

t1.start()
TypeError:“int”对象不可调用

这里有一个使用对象的解决方案

使用条件变量的典型编程样式使用锁 同步对某些共享状态的访问;线程是 对状态的特定更改感兴趣重复调用wait() 直到看到所需的状态,而修改状态的线程 以这种方式更改状态时,调用notify()或notifyAll() 这可能是一个服务员想要的状态

预期的执行序列是(t1,t3,t1,t2,t1,t3,…),因此我们只需创建一个保存当前状态的状态变量,并且只有在满足预期条件时,每个线程才会工作。之后,它将更新状态并唤醒其他线程

from threading import Thread, Lock, Condition


def zero_printer(max_iters):
    global state
    for _ in range(max_iters):
        with cv:
            while state not in (0, 2):
                cv.wait()
            state += 1
            print('0')
            cv.notify_all()


def even_printer(max_iters):
    global state
    c = 2
    for _ in range(max_iters):
        with cv:
            while state != 3:
                cv.wait()
            print(c)
            state = 0
            cv.notify_all()
        c += 2


def odd_printer(max_iters):
    global state
    c = 1
    for _ in range(max_iters):
        with cv:
            while state != 1:
                cv.wait()
            print(c)
            state = 2
            cv.notify_all()
        c += 2


iters = 3
state = 0
cv = Condition(Lock())

t1 = Thread(target=zero_printer, args=(iters * 2,))
t2 = Thread(target=even_printer, args=(iters,))
t3 = Thread(target=odd_printer, args=(iters,))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()
结果:

0
1
0
2
0
3
0
4
0
5
0
6
我没有费心把它合并成一行

代码中的错误是您误用了
线程。Thread
即传递一个整数值作为expectet目标参数,因此它试图执行您的int值并生成相应的错误消息