Search code examples
pythonpython-3.xpython-2.7python-requestspython-multithreading

Thread library in the following code isn't work


what's the problem in the code below? It only shows two arrows when I run it Of course, the first was the import thread, but because it gave an error (no module named 'thread'), I changed it to import threading

import threading
import turtle

def f(painter):
    for i in range(3):
        painter.fd(50)
        painter.lt(60)

def g(painter):
    for i in range(3):
        painter.rt(60)
        painter.fd(50)

try:
    pat=turtle.Turtle()
    mat=turtle.Turtle()
    mat.seth(180)
    thread.start_new_thread(f,(pat,))
    thread.start_new_thread(g,(mat,))
    turtle.done()

except:
    print("hello")

while True:
    pass

enter image description here


Solution

  • threaing and thread are separate modules to deal with threads in python. However thread module is considered as deprecated in python3 but renamed to _thread for backward compatibility. In your case i assume you are trying to use _thread module with python3.

    So your code should be as follows.

    import _thread
    import turtle
    
    def f(painter):
        for i in range(3):
            painter.fd(50)
            painter.lt(60)
    
    def g(painter):
        for i in range(3):
            painter.rt(60)
            painter.fd(50)
    
    try:
        pat=turtle.Turtle()
        mat=turtle.Turtle()
        mat.seth(180)
        _thread.start_new_thread(f,(pat,))
        _thread.start_new_thread(g,(mat,))
        turtle.done()
    except:
        print("Hello")
    
    while True:
        pass
    

    since _thread module is deprecated, it is better you move to threading module.