rust怎么使用thread::current()修改线程名
时间: 2023-06-05 09:09:10 浏览: 60
使用thread::current().name()获取当前线程的名称,再使用thread::Builder设置线程名称,具体实现代码如下:
```
use std::thread;
fn main() {
let child_thread = thread::Builder::new()
.name("My Child Thread".into())
.spawn(move || {
let current_thread = thread::current();
println!("Child thread before modification: {:?}", current_thread.name());
current_thread
.name()
.expect("Thread has no name!")
.to_string()
.chars()
.enumerate()
.for_each(|(i, character)| {
current_thread
.name_mut()
.unwrap()
.as_bytes_mut()
[i] = character as u8
});
println!("Child thread after modification: {:?}", current_thread.name());
})
.unwrap();
child_thread.join().unwrap();
}
```
其中,thread::Builder设置线程名时需要将字符串转换成String类型,然后使用.into()方法转换为OsString类型。使用thread::current().name()获取当前线程名称,再使用thread::current().name_mut()获取可变引用修改线程名称,修改完后使用println!()输出即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)