【问题标题】:Why arguments of threads sometimes confuse in Python?为什么线程的参数有时会在 Python 中混淆?
【发布时间】:2016-01-22 21:30:53
【问题描述】:

我编写基本线程程序:

import threading 

初始化线程

class OpenThread (threading.Thread):
    def __init__(self, threadID):
        threading.Thread.__init__(self)
        self.threadID = threadID

    def run(self):
        print thread.threadID

for tID in range(0, 5):
    thread = OpenThread(tID)
    thread.start()

最后 5 个尝试的输出在这里:

####try 1 
0
1
2
3
4

####try 2 
0
1
 2
3
4

####try 3 
0
2
23

4



####try 4 

0
1
2
3
 4

####try 5 

0
1
3
 34

我使用 PyCharm 作为 IDE。 我不明白为什么会有空格字符以及为什么更多线程参数得到相同的值

【问题讨论】:

    标签: python multithreading python-2.7 pycharm python-multithreading


    【解决方案1】:

    请阅读更多关于打印线程安全

    问题在于 python 使用单独的操作码进行 NEWLINE 打印和对象本身的打印。最简单的解决方案可能只是使用显式 sys.stdout.write 和显式换行符。或者使用锁并重新绑定“打印”!或者使用日志系统! .

    from __future__ import print_function
    print = lambda x: sys.stdout.write("%s\n" % x)
    

    import threading
    import logging
    
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger('thread-safe')
    
    class OpenThread (threading.Thread):
        def __init__(self, threadID):
            threading.Thread.__init__(self)
            self.threadID = threadID
    
        def run(self):
            logger.debug(thread.threadID)
    
    for tID in range(0, 5):
        thread = OpenThread(tID)
        thread.start()
    

    python3 中的打印是安全的。

    【讨论】:

    • 打印线程不安全也会破坏输出吗?似乎输出中的数字也不正确,不考虑新行。
    • @all3g 我可以理解换行问题,我不在乎。但我不理解输出中显示的空格字符和线程的相同参数值。我试过你的代码,线程仍然得到相同的 threadID 值。
    • 请将 thread.threadID 更正为 self.threadID
    • 如果我在 thread.start() 之后添加 thread.join(),如果没有一个线程完成,则无法创建另一个线程。这抵消了多线程的优势,我希望所有线程一起工作。
    • 不知道为什么,用self.threadID代替thread.threadID,解决同值问题。但空格字符问题仍然存在。
    猜你喜欢
    • 2010-09-29
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多