[Python] Why the print line will exec twice in a py file? [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    When learning python threading and process some wired code i do not understand

    The question is

    1. why the print line exec twice?
    2. why gvar is 20 in proc1 init but gvar is 10 in proc1 run?

    can anyone explain the principle why is it

    The sample code and output follows

    import multiprocessing
    import os
    import threading
    from multiprocessing import freeze_support

    print('why this will print twice? pid {} tid {}'.format(os.getpid(), threading.get_ident()))
    gvar = 10


    class Proc1(multiprocessing.Process):
    def __init__(self):
    super().__init__()
    print('proc1 init pid {} tid {} gvar {}'.format(os.getpid(), threading.get_ident(), gvar))

    def run(self) -> None:
    print('proc1 run pid {} tid {} gvar {}'.format(os.getpid(), threading.get_ident(), gvar))


    class Thread1(threading.Thread):
    def __init__(self):
    super().__init__()
    print('thread1 init pid {} tid {} gvar {}'.format(os.getpid(), threading.get_ident(), gvar))

    def run(self) -> None:
    print('thread1 run pid {} tid {} gvar {}'.format(os.getpid(), threading.get_ident(), gvar))


    if __name__ == '__main__':
    freeze_support()
    print('pid {} tid {} gvar {}'.format(os.getpid(), threading.get_ident(), gvar))

    s = Thread1()
    s.start()

    gvar = 20

    p = Proc1()
    p.start()



    and the out put is

    why this will print twice? pid 38648 tid 31428
    pid 38648 tid 31428 gvar 10
    thread1 init pid 38648 tid 31428 gvar 10
    thread1 run pid 38648 tid 26968 gvar 10
    proc1 init pid 38648 tid 31428 gvar 20
    why this will print twice? pid 27380 tid 19716
    proc1 run pid 27380 tid 19716 gvar 10

    Continue reading...

Compartilhe esta Página