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

Take slice of certain length known at compile time
Is it possible to deactivate file locking in cargo?
“does not live long enough” error in same function
What ways exist to create containers of several types? [duplicate]
How can I optimize reading a UTF-8 string from a file with a known offset and size?
Create vector of objects implementing a trait in Rust
Using loop variable from “..” loop causes type conversion?
What is RFC 401's coerce_inner useful for?
Rust Borrow checker only complains about borrowing as mutable multiple times when a function that returns a reference with the same lifetime assigned
How can I remove `let _ : () = …`?
Does if-let with a pair short-circuit?
Rust borrow lasts beyond the scope it's in?
How can I include an arbitrary set of Protobuf-built files without knowing their names?
Specialization of method in inherent impl
Getting reference to object behind Rc
Similar implementations of one trait for many structs

Categories

HOME
mc
azure-functions
schema.org
qc
command-prompt
ews
yql
implicit-conversion
angular-meteor
jpa-criteria
gtk
colors
amazon-elb
sonata
google-cloud-logging
jqxgrid
bluemix-mobile-services
social-tables
spring-ldap
data-type-conversion
quantitative-finance
software-packaging
fstar
running-object-table
onchange
react-bootstrap-table
materialize
region
google-play-developer-api
objectmapper
nsmutablearray
cucumber-junit
private-key
nest
image-optimization
pdfminer
numerics
aurelia-cli
cloudera-quickstart-vm
strapi
microsoft-ui-automation
sbjson
google-prediction
audio-converter
spongycastle
sonarqube5.2
sony-future-lab-n
embedded-v8
test-data
stateless-session-bean
dtd
cognos-tm1
google-shopping-api
qtextedit
openseadragon
oci
node.js-connect
codecharge
highlighting
verisign
gridbaglayout
ambiguity
highest
auto-generate
gluon-desktop
netdatacontractserializer
supersocket.net
explain
subfolder
maven-shade-plugin
createfile
lmax
nidaqmx
csslint
.htpasswd
reference-counting
windows-taskbar
strdup
strcmp
grails-2.3
libxml-js
flv
eager-loading
spark-view-engine
sfinae
websphere-6.1
image-scanner
datacontracts
aptitude
tessellation
uninstaller
android-input-method
self-tracking-entities
powergui
projectpier
jquery-effects
sqlsitemapprovider
ning
html-generation

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App