扩展了我之前提出的关于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不是这样
我试图只使用一个进程,但它仍然安全地打印每一行都打印在一个新行中,但是当我显式调用startThreads
时,它的行为不一样,也不安全打印,它的行为是这样吗?!在
使用相同的代码,我得到
scrambled
输出:尝试运行多次。如果1和2总是加扰的-可能是平台相关的。在
它没有同步。顺序是随机的:)
相关问题 更多 >
编程相关推荐