【问题标题】:unable to create a thread in python无法在python中创建线程
【发布时间】:2012-04-28 13:56:57
【问题描述】:

我有以下比较用户输入的代码

import thread,sys
if(username.get_text() == 'xyz' and password.get_text()== '123' ):
   thread.start_new_thread(run,()) 

def run():
  print "running client"
  start = datetime.now().second
  while True:
    try:
        host ='localhost'
        port = 5010
        time = abs(datetime.now().second-start)
        time = str(time)
        print time
        client = socket.socket()
        client.connect((host,port))
        client.send(time)
    except socket.error:
        pass

如果我只是调用函数 run() 它可以工作,但是当我尝试创建一个线程来运行这个函数时,由于某种原因没有创建线程并且没有执行 run() 函数我找不到任何错误..

提前谢谢...

【问题讨论】:

  • 你能提供一个最小的运行示例吗?此代码不会运行,因为名称 usernamepassword 未定义。

标签: python multithreading sockets client


【解决方案1】:

你真的应该使用threading 模块而不是thread

你还在做什么?如果你像这样创建一个线程,那么无论线程是否仍在运行,解释器都会退出

例如:

import thread
import time

def run():
    time.sleep(2)
    print('ok')

thread.start_new_thread(run, ())

--> 这会产生:

Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr

如:

import threading
import time

def run():
    time.sleep(2)
    print('ok')

t=threading.Thread(target=run)
t.daemon = True  # set thread to daemon ('ok' won't be printed in this case)
t.start()

按预期工作。如果您不想让解释器等待线程,只需在生成的线程上设置 daemon=True*。

*edit: 在例子中添加了

【讨论】:

  • 我知道thread.start_new_thread是一个有限的库,我最初使用threading.thread,创建线程并调用run函数,但问题是代码在while循环中被敲击。线程的整个目的都被打败了,所以我尝试使用thread.start_new_thread。简而言之,我的问题仍然没有解决。当我在我的代码中创建一个线程时,代码在 while 循环中被击中。另外请尝试解决我的代码,我知道您给出的 run() 定义很简单并且有效。
  • 当然卡在一个循环中。如果你不想要那样,你必须有办法以某种方式结束线程。 this 通过将线程设置为守护线程来工作,这意味着当没有其他(非守护)线程正在运行时,它将被杀死。
  • 你能解释一下那个wid一些代码吗,我听说过守护线程但不知道如何使用它..谢谢回复
【解决方案2】:

thread 是一个低级库,你应该使用threading

from threading import Thread
t = Thread(target=run, args=())
t.start()

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 2011-02-23
    • 2012-01-11
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多