Starting threads inside class

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 23 15:31:15 PST 2016


On 02/23/2016 07:31 AM, Josh wrote:
 > My goal with the code below is to eventually have my main communicate
 > with Foo and Bar classes listening for packets on a different
 > address/port, each in a separate thread.

The main issue is that in D all data is thread-local by-default. main() 
cannot create objects and then implicitly give access to those objects 
from other threads.

 > the most I would be doing from outside is accessing the Tid in order
 > to send packets from my main.

Even that's not needed because spawn() returns the Tid. And you don't 
need to pass ownerTid, it is already available to child threads.

Options:

a) spawn() a thread by passing necessary data for it to create a Foo. 
(Preferred.)

b) In case main() needs to have access to the objects, construct objects 
as shared(Foo) and pass references to threads.

Here is the code with option a:

import std.socket;
import std.concurrency;

void daemon()
{
     auto f = new Foo();

     f.setup();
     f.initialise();
     long rxSize = -1;
     while (true)
     {
         rxSize = f.mysock.receive(f.buffer);
         if (rxSize == 0)
         {
             break;
         }
         f.packetHandler();
     }
     f.closeConnection();
}

class Foo
{
     private string address = "127.0.0.1";
     private ushort port = 55555;
     private ubyte[256] buffer;
     private TcpSocket mysock;
     Tid listenerd;

     void setup()
     {
         mysock = new TcpSocket();
         mysock.blocking = true;
         try
         {
             mysock.connect(new InternetAddress(address, port));
         }
         catch (SocketOSException e)
         {
         }
     }

     void initialise()
     {
         // send init packet
     }

     void closeConnection()
     {
         // send close packet
     }

     void packetHandler()
     {
         // do something with buffer
     }

}

void main() {
     auto listenerd = spawn(&daemon);
}

Ali



More information about the Digitalmars-d-learn mailing list