【问题标题】:Python using multithreadingPython 使用多线程
【发布时间】:2021-08-10 09:01:28
【问题描述】:
import threading
from time import time

def count(n):
    for i in range(1,n+1):
        print(i)


def count2(n):
    for i in range(1,n+1):
        print(i)

def count3(n):
    for i in range(1,n+1):
        print(i)





x = threading.Thread(target=count,args=(10,))
x.start()

y  = threading.Thread(target=count2,args=(10,))
y.start()

y  = threading.Thread(target=count3,args=(10,))
y.start()

我决定学习python多线程,我发现这段代码和输出是

1
2
3
1
4
1
2
2
3
3
5
4
6
5
7
8
6
9
4
5
6
7
8
9
10
7
8
9
10
10

谁能解释一下为什么是这个输出?它是如何工作的? 我想用 selenium 运行多线程。

了解多线程如何在 python3 中工作的最佳方法是什么

【问题讨论】:

  • 好吧,这段代码启动了 3 个线程,每个线程打印从 1 到 10 的数字。线程并行工作,因此输出没有顺序。
  • 您能否澄清一下您了解的输出的哪些部分?想必您对自己编写的程序的功能有所期待吧?

标签: python python-3.x multithreading


【解决方案1】:

它看起来正常且运行正常。您可以理解“线程”,因为它为编程流程一起运行准备了不同的路径。由于并行运行,系统将无法正常运行。如果假设您想按某个顺序排列,那么您需要有一些变通方法使其看起来更“美观”,如 Python 中的事件函数“Event.Set()”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2016-08-03
    • 2017-01-27
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多