在Python中,你可以使用`threading`模块的`current_thread()`函数来获取当前线程的ID。下面是一个简单的示例代码:
```python
import threading
获取当前线程ID的函数
def print_current_thread_id():
thread_id = threading.current_thread().ident
print("当前线程的ID为:", thread_id)
在主线程中调用函数
print_current_thread_id()
创建一个新线程并调用函数
thread = threading.Thread(target=print_current_thread_id)
thread.start()
thread.join()
当你运行这段代码时,你会看到类似以下的输出:
```
当前线程的ID为: 2448
当前线程的ID为: 8144
这表明主线程和新创建的线程都有各自独立的ID。