www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Need to synchronize Socket.send()?

reply Max Kaufmann <max.kaufmann gmail.com> writes:
Consider this threaded socket server:

import std.stdio;
import std.string;
import std.socket;
import std.thread;

void main() {
	char[] ip = "127.0.0.1";
	int port = 12345;
	WorkerThread[] threads = [];
	writefln("Listening on "~ip~":"~toString(port));
	InternetAddress addr = new InternetAddress(ip,port);
	Socket sock = new TcpSocket();
	scope(exit) sock.close();
	sock.bind(addr);
	sock.listen(1);
	while(1) {
		WorkerThread worker = new WorkerThread(sock.accept());
		worker.start();
	}
}

class WorkerThread : Thread {
	private:
		Socket conn;
	public:
		this(Socket conn) {
			super();
			this.conn = conn;
			writefln("Spawning New Thread.");
		}

		int run() {
			byte[] bytesToSend = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
			conn.send(bytesToSend);
			return 0;
		}
}

Is Socket.send() synchronized, or do I need to synchronize it myself?
Aug 19 2007
next sibling parent Brad Roberts <braddr puremagic.com> writes:
Max Kaufmann wrote:
 Consider this threaded socket server:
 
 import std.stdio;
 import std.string;
 import std.socket;
 import std.thread;
 
 void main() {
 	char[] ip = "127.0.0.1";
 	int port = 12345;
 	WorkerThread[] threads = [];
 	writefln("Listening on "~ip~":"~toString(port));
 	InternetAddress addr = new InternetAddress(ip,port);
 	Socket sock = new TcpSocket();
 	scope(exit) sock.close();
 	sock.bind(addr);
 	sock.listen(1);
 	while(1) {
 		WorkerThread worker = new WorkerThread(sock.accept());
 		worker.start();
 	}
 }
 
 class WorkerThread : Thread {
 	private:
 		Socket conn;
 	public:
 		this(Socket conn) {
 			super();
 			this.conn = conn;
 			writefln("Spawning New Thread.");
 		}
 
 		int run() {
 			byte[] bytesToSend = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 			conn.send(bytesToSend);
 			return 0;
 		}
 }
 
 Is Socket.send() synchronized, or do I need to synchronize it myself?

In your example, each connection is it's own unique socket, so there's no need to sync on anything. Later, Brad
Aug 19 2007
prev sibling parent reply BCS <ao pathlink.com> writes:
Reply to Max,

 Consider this threaded socket server:
 

 Is Socket.send() synchronized, or do I need to synchronize it myself?
 

I'm no expert, but I'd guess not, each thread will get it's own socket, so that shouldn't be a problem and I'd be surprised if Socket.send is not thread safe.
Aug 19 2007
parent BCS <ao pathlink.com> writes:
Reply to Benjamin,

 Reply to Max,
 
 Consider this threaded socket server:
 

 Is Socket.send() synchronized, or do I need to synchronize it myself?
 


that you will
 not

need to syncroniz it
, each thread will get it's own
 socket, so that shouldn't be a problem and I'd be surprised if
 Socket.send is not thread safe.
 

x-b
Aug 19 2007