rust


How can I pass a socket as an argument to a function being called within a thread?


I'm going to have multiple functions that all need access to one main socket.
Would it better to:
Pass this socket to each function that needs access to it
Have a globally accessible socket
Can someone provide an example of the best way to do this?
I come from a Python/Nim background where things like this are easily done.
Edit:
How can I pass a socket as an arg to a function being called within a thread.
Ex.
fn main() {
let mut s = BufferedStream::new((TcpStream::connect(server).unwrap()));
let thread = Thread::spawn(move || {
func1(s, arg1, arg2);
});
while true {
func2(s, arg1);
}
}
Answer for updated question
Rust 1.0
We must use try_clone nowadays.
use std::io::Read;
use std::net::{TcpStream,Shutdown};
use std::thread;
fn main() {
let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
let stream2 = stream.try_clone().unwrap();
let _t = thread::spawn(move|| {
// close this stream after one second
thread::sleep_ms(1000);
stream2.shutdown(Shutdown::Read).unwrap();
});
// wait for some data, will get canceled after one second
let mut buf = [0];
stream.read(&mut buf).unwrap();
}
Original Answer
You can simply clone the socket. Here's an example direct from the documentation:
use std::old_io::timer;
use std::old_io::TcpStream;
use std::time::Duration;
use std::thread::Thread;
let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
let stream2 = stream.clone();
let _t = Thread::spawn(move|| {
// close this stream after one second
timer::sleep(Duration::seconds(1));
let mut stream = stream2;
stream.close_read();
});
// wait for some data, will get canceled after one second
let mut buf = [0];
stream.read(&mut buf);
Original answer
It's usually (let's say 99.9% of the time) a bad idea to have any global mutable state, if you can help it. Just do as you said: pass the socket to the functions that need it.
use std::old_io::{IoResult,TcpStream};
fn send_name(stream: &mut TcpStream) -> IoResult<()> {
try!(stream.write(&[42]));
Ok(())
}
fn send_number(stream: &mut TcpStream) -> IoResult<()> {
try!(stream.write(&[1, 2, 3]));
Ok(())
}
fn main() {
let mut stream = TcpStream::connect("127.0.0.1:31337").unwrap();
let r =
send_name(&mut stream)
.and_then(|_| send_number(&mut stream));
match r {
Ok(..) => println!("Yay, sent!"),
Err(e) => println!("Boom! {}", e),
}
}
You could also pass the TcpStream to a struct that manages it, and thus gives you a place to put similar methods.
use std::old_io::{IoResult,TcpStream};
struct GameService {
stream: TcpStream,
}
impl GameService {
fn send_name(&mut self) -> IoResult<()> {
try!(self.stream.write(&[42]));
Ok(())
}
fn send_number(&mut self) -> IoResult<()> {
try!(self.stream.write(&[1, 2, 3]));
Ok(())
}
}
fn main() {
let stream = TcpStream::connect("127.0.0.1:31337").unwrap();
let mut service = GameService { stream: stream };
let r =
service.send_name()
.and_then(|_| service.send_number());
match r {
Ok(..) => println!("Yay, sent!"),
Err(e) => println!("Boom! {}", e),
}
}
None of this is really Rust-specific, these are generally-applicable programming practices.

Related Links

Join futures with limited concurrency
How to get Racer working with Atom?
How do I compile the raw-cpuid crate in rust?
Anonymous enum in Rust
Lifetime of references in closures
Why can't the Option.expect() message be downcast as a &'static str when a panic is handled with catch_unwind?
Why does the Rust documentation say that sharing a reference to a vector would create an invalid vector even though the vector is on the heap?
Polymorphism in Rust and trait references (trait objects?)
Setting the include path with bindgen
In Rust, how can a reference be a pointer to a pointer-to-a-pointer?
How to join thread in drop function? [duplicate]
Blanket implementation of core traits constrained by locally-defined public trait
Why does this Rust program ignore immutability
Pointer dereferencing in Rust
Cannot borrow data mutably in a `&` reference in array
How to cleanly break tokio-core event loop and futures::Stream in Rust

Categories

HOME
hpoo
knockout.js
tomcat
facebook-messenger
subdomain
mosquitto
static-analysis
hspi
stack-overflow
driver
business-intelligence
mailmerge
responsivevoice
twisted
mixpanel
adminlte
kaggle
rxjs5
device
software-packaging
mod-wsgi
managed-c++
data-collection
tsung
source-insight
phpstorm-2016.1
nsmutablearray
cucumber-junit
restful-architecture
variable-variables
aurelia-http-client
oauth2
word-cloud
bit-shift
spongycastle
deployd
karabiner
msxml
google-shopping-api
fuzzer
dpkg
distributed-cache
teamviewer
wikimedia-commons
flask-security
decidable
ruby-on-rails-4.1
blank-line
jnlp
featuretoggle
fantom
whitespace-language
nssortdescriptor
mod-auth-openidc
fasterxml
hp-idol-ondemand
string.format
git-reset
jini
rails-api
proxy-server
hyphen
colon
ggts
frontbase
rautomation
insertion
chefspec
xmlwriter
cyrillic
taskkill
algol68
netstream
n-queens
infopath-2007
servercontrol
data-dump
representation
nsrangeexception
azure-acs
cewolf
jdownloader
urchin
prism-2
server-load
webclient.uploaddata

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App