python RuntimeError:cannot join current thread 错误:无法加入当前进程

笔者环境 python3.7+tqdm4.28.1

在运行程序的时候老是会报错

RuntimeError:cannot join current thread

原因:参考_1,参考_2

解决方法:

定位到你安装的tqdm包,一般都是安装在site-packages/tqdm中,然后找到_monitor.py文件,打开在以下内容中做出修改

from threading import Event,Thread,current_thread #第一行修改为这样
.
.
.
def exit(self):                                   #50行之后的exit函数修改为这样
        self.was_killed.set()
        if self is not current_thread():
            self.join()
        return self.report()

很奇怪,当我在win10中查找的_monitor文件时已经修改好了的,可能是4.31.1新版本已经修改好了这个bug,但是tensorflow环境下的版本应该还是会出问题。

(base) C:\Users\Lenovo>activate tensorflow

(tensorflow) C:\Users\Lenovo>python
Python 3.6.7 |Anaconda, Inc.| (default, Oct 28 2018, 19:44:12) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tqdm
>>> tqdm.__version__
'4.28.1'
>>> exit()

(tensorflow) C:\Users\Lenovo>activate torch

(tensorflow) C:\Users\Lenovo>conda.bat activate torch

(torch) C:\Users\Lenovo>python
Python 3.6.8 |Anaconda, Inc.| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tqdm
>>> tqdm.__version__
'4.31.1'
>>>

可能是新版本的tqdm(4.31.1)已经修改好了这个bug

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误通常是因为你在主线程中调用了当前线程的 `join()` 方法导致的。在 Python 中,每个线程都有一个线程 ID,主线程的线程 ID 是 `MainThread`,而其他线程的线程 ID 是一个整数。如果你在主线程中调用当前线程的 `join()` 方法,就相当于在主线程中等待主线程自己执行完毕,因此就会出现这个错误。 为了避免这个错误,你可以在调用 `join()` 方法之前先判断当前线程是否是主线程。具体代码如下: ```python import threading def worker(): print("Worker is running") t = threading.Thread(target=worker) t.start() # 等待线程执行完毕 if t != threading.current_thread(): t.join() ``` 在上面的代码中,我们首先创建了一个新线程 `t`,并将 `worker()` 函数作为参数传递给它。接着,我们通过判断 `t` 是否是当前线程来决定是否调用 `join()` 方法。如果 `t` 不是当前线程,就调用 `join()` 方法等待线程 `t` 执行完毕;否则就跳过 `join()` 方法,避免出现 `RuntimeError: cannot join current thread` 错误。 另外,你也可以使用 `threading.main_thread()` 函数来获取主线程对象,从而更加直观地判断当前线程是否是主线程。具体代码如下: ```python import threading def worker(): print("Worker is running") t = threading.Thread(target=worker) t.start() # 等待线程执行完毕 if t != threading.main_thread(): t.join() ``` 在上面的代码中,我们使用 `threading.main_thread()` 函数来获取主线程对象,然后将其与当前线程进行比较,避免了出现 `RuntimeError: cannot join current thread` 错误

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值