【问题标题】:Create two threads创建两个线程
【发布时间】:2017-04-06 12:05:25
【问题描述】:

创建两个线程(我们称它们为 T1 和 T2)。 T1 应该打印“I am T1”,T2 应该打印“I am T2”。主线程(创建 T1 和 T2 的线程)应该等待它们。 o 应该有一个共享变量 x 初始化为 10。T1 应该将 x 增加 5,T2 应该增加 x 100。 o 然后,在 T1 和 T2 完成后,主进程应该打印“我是主线程,两条线都完成了”。此外,主线程应该打印 x 的最后一个值。

【问题讨论】:

  • 这听起来像是一个家庭作业问题。你想让我们为你做你的工作吗?你自己写过代码吗?如果是这样,请将其添加到您的帖子中,并告诉我们您在使用它时遇到了什么问题。
  • @Ahmad 欢迎来到stackoverflow,你有没有尝试一下,也许是你的代码的粗略轮廓
  • 好的,创建两个线程。
  • 对了!我可以在哪里提交作业以获得我的学分?

标签: python python-2.7 python-3.x operating-system computer-science


【解决方案1】:

我不知道你的问题是什么,但让我试试:

  1. 您需要创建 T1 和 T2
  2. t1 和 t2 应该在构造函数上打印 'i am..' 消息
  3. 两个线程都应该增加相同的 x 变量
  4. 然后在这两个人完成后,主线程打印一条消息
  5. 主线程需要打印x值

这里是:

import threading

x = 10

class T1 (threading.Thread):
    def __init__(self):
        super(T1 , self).__init__(name="T1 thread")
        print 'I am T1'

    def run(self):
        global x
        x += 5


class T2 (threading.Thread):
    def __init__(self):
        super(T2 , self).__init__(name="T2 thread")
        print 'I am T2'

    def run(self):
        global x
        x += 100

t1 = T1()
t2 = T2()

t1.start()
t2.start()

while t1.is_alive() or t2.isAlive():
    pass

print "t1 and t2 are done"
print x

因为您不使用任何应该工作的列表或数据结构,但如果您假装使用任何列表、行、堆栈等,请记住检查此链接。 Python Multithreaded Programming

【讨论】:

    【解决方案2】:

    这应该可行。

    import threading
    x = 10
    def prints(Text,increment):
        global x
        print Text
        x += increment
    
    thread1 = threading.Thread(target=prints, args=("I am T1\n",5))
    thread2 = threading.Thread(target=prints, args=("I am T2\n",100)) #Create threads and pass arguments to function
    thread1.start()
    thread2.start()             #Start threads
    
    thread1.join()      #Wait until thread1 has finished execution
    thread2.join()      #Wait until thread2 has finished execution
    print "I am the main thread, the two threads are done"
    print x
    raw_input("") #Just to prevent window from closing
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2012-08-20
      • 1970-01-01
      相关资源
      最近更新 更多