I am trying to serve multiple TCP connections and encapsulate the server for each connection into a class handling its own socket.
1) The main thread starts a TCP connection server, to accept incoming connections
2) The TCP connection server accepts new connections, creates a new object for each connection, adds the handle to an array of connection objects, and forks the connection handler thread
3) the object connection handler then handles the connection itself
My main application is actually distributing a data stream onto several TCP clients. Therefore, my main thread must serve a send buffer with data to be used by the connection handler threads. For cleaner coding (and due to the low total number of connections), I decided to create a separate send buffer for each connection.
The main thread and the connection handler threads need to acquire a lock on the connection object's send buffer. Therefore I make the objects blessed self-reference shared, and can acquire a lock on the objects reference both from the main thread as well as from within the objects methods (rudimentary object example code below).
Problem: the TCP connection handler gets an open socket from the IO::Socket::INET accept() method. When I try to pass this open socket as an argument to my object constructor, the interpreter complains about an Invalid value for shared scalar in the constructor, because apparently it is not allowed to share a socket variable.
I am somewhat at a loss, because I don't actually want to share the *socket* itself, I simply want to acquire a lock on the buffer variables of my connection object. Is there another way to do this for thread-safe handling of the send buffer per object?
Thanks in advance!
Example for connection class:
{ package IPConnection; use threads; use threads::shared; use Time::HiRes qw(time sleep); sub new { my $class = shift; my $arg = shift; share (my %this); $this{_socket} = shift; $this{_sendBufferCount} = 0; bless \%this, $class; return \%this; } sub handleConnection { my $this = shift; my $someData = "foo"; { # scope for lock on $this lock ($this); push @{$this->{_sendBuffer}}, $someData; # manipulate the + send buffer $this->{_sendBufferCount}++; # manipulate the + send buffer } # release lock } }
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |