0

I have 2 Vec as server_stream_vec, client_stream_vec I want to use them multiple times inside loop. So I tried to use Arc.

What I did:

let stream_vec_arc = Arc::new((server_stream_vec, client_stream_vec));
    let stream_vec_clone = Arc::clone(&stream_vec_arc);

For testing I tried to unwrap it:

let (server_stream_vec, client_stream_vec) = Arc::try_unwrap(stream_vec_clone).unwrap();

But the unwrap panics. I dont have any other Arc in the code.

Please let me know what is the issue.

A similar code (in a separate project I created to test) also giving the same error:

fn main() {

    let vector: Vec<u8> = vec![1,2,4,7];

    let stream_vec_arc = Arc::new(vector);
    let stream_vec_clone = Arc::clone(&stream_vec_arc);

    let val = Arc::try_unwrap(stream_vec_clone).unwrap();

    println!("{:?}", val);
    
}

error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: [1, 2, 4, 7]',
Zubayr
  • 457
  • 4
  • 18
  • can you share the full minimal reproducible example code? you mentioned a loop, but I see no loop. maybe als share a rust playground link https://play.rust-lang.org – Simon Laux Aug 05 '23 at 21:32
  • @SimonLaux I shared the code. its a bit complicated. But you can see the use of Arc in line 201 inside initiate function. And the loop is between line 257-270 (currently commented out). You may ignore the ohter functions and just check the initiate. – Zubayr Aug 05 '23 at 21:39
  • What is the end goal here? This will obviously fail because `try_unwrap()` only succeed if there is *only one* `Arc` owning the data, and you have two. – kmdreko Aug 05 '23 at 22:41
  • @kmdreko I edited the code so that you can check a smipler code. – Zubayr Aug 05 '23 at 22:45
  • @kmdreko I am trying to clone the Vec since its a vec of generics where .clone() doesnt work. And I need to move this variable into multiple different functions/ loops. This is why I am trying to use Arc::clone() to clone it. and Arc::try_unwrap to unwrap the actual vector (so that I can use the vector in those functions/ loops) – Zubayr Aug 05 '23 at 22:47
  • What are you trying to do with `val` after attempting to pull it out of the `Arc`? You don't need to do that if you only need immutable access and if you want to modify it you should put it in a mutex (i.e. `Arc>>`). – kmdreko Aug 05 '23 at 22:53
  • Actually I am passing the vec in a tokio::spawn. Inside the spawn there is a for loop. And inside the loop I am taking specific elements from the vec (so for 1st iteration I am taking 0th element and so on). If I pass the vec as it is inside the loop, I am getting value moved error. – Zubayr Aug 05 '23 at 22:58
  • Then you should put it in a mutex. If you include some code for what you just described, that would make it easier to give you a more direct answer. – kmdreko Aug 05 '23 at 23:20

0 Answers0