在python中实现在多个进程上启动多个线程的代码

2024-06-16 11:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

扩展了我之前提出的关于python中多进程之上的多线程的问题

Can I do multithreads on each process of a multiprocess program?

所以我尝试实现一个实现这个目标的例子。首先,我生成2个进程,每个进程将在其中创建10个线程,但有些东西看起来不对劲。我没有实现任何类型的锁或信号量,所以我希望输出被置乱(如示例3所示)。当我运行这段代码时,示例1和2以正确的格式打印。例如,我甚至尝试创建2个线程来启动每个进程,以确保它们不是按顺序启动的!为什么会这样?我遗漏了什么?协调发生在哪里?在

import multiprocessing, threading, time

def startThreads(n):
    threads = [threading.Thread(target=printer, args=(n, i))  for i in range(10)]
    [t.start() for t in threads]
    [t.join() for t in threads]

def printer(process_num, thread_num):
    time.sleep(1)
    print(f"Process number: {process_num} thread number: {thread_num}")
    print(f"Process number: P thread number: T")

if __name__ == '__main__':

    # Example 1
    pros = [multiprocessing.Process(target=startThreads, args=(p_num, )) for p_num in range(5)]
    [p.start() for p in pros]
    [p.join() for p in pros]
    # Process number: 0 thread number: 0
    # Process number: P thread number: T
    # Process number: 0 thread number: 4
    # Process number: P thread number: T
    # Process number: 0 thread number: 1
    # Process number: P thread number: T
    # Process number: 0 thread number: 2
    # Process number: P thread number: T
    # Process number: 0 thread number: 3
    # Process number: P thread number: T
    # Process number: 1 thread number: 0
    # ...

    # Example 2
    print()
    startThreads(0)
    # Process number: 0 thread number: 1
    # Process number: P thread number: TProcess number: 0 thread number: 0
    # Process number: P thread number: T

    # Process number: 0 thread number: 2Process number: 0 thread number: 4Process number: 0 thread number: 3
    # Process number: P thread number: T

    # Process number: P thread number: T

    # Process number: P thread number: T

请注意,在示例2中print的行为是如何的,另一方面,示例1总是以正确的格式(安全打印)打印,而在这两种情况下,print函数是由线程调用的,当我删除打印格式并使用固定字符串打印时,会发生同样的情况。在

As the discussion in this question says我们需要实现某种安全的打印方法来获得新行中的每个print语句,但示例1不是这样


^{pr2}$

我试图只使用一个进程,但它仍然安全地打印每一行都打印在一个新行中,但是当我显式调用startThreads时,它的行为不一样,也不安全打印,它的行为是这样吗?!在


Tags: in示例numberfor进程格式线程process
1条回答
网友
1楼 · 发布于 2024-06-16 11:04:10

使用相同的代码,我得到scrambled输出:

1:20:21:3, , 0:00:1, 0:71:5, , 1:40:91:1, 1:6, , , 1:0, , 0:5, 0:4, 0:3, 0:6, 1:7, 0:8, 1:9, , 1:8, 
0:0, 0:10:2, , 0:3, 0:4, 0:50:6, 1:0, , 1:1, 0:7, 1:2, 1:3, 0:9, 0:81:5, 1:4, , 1:71:6, , 1:91:8, , 
0:0, 0:1, 0:40:3, 0:2, , 0:60:5, , 0:70:8, , 0:9, 

尝试运行多次。如果1和2总是加扰的-可能是平台相关的。在

so I expect the output to be scrambled

它没有同步。顺序是随机的:)

相关问题 更多 >