PTypes: multithreading: examples

Top: Multithreading: Examples

Example 1. This simple example shows the use of mutex objects to safely perform calculation that involves more than one global variable. Note that using the rwlock class instead of mutex can improve performance by allowing multiple threads call avg_get() at once.

>     int avg_sum = 0;
>     int avg_cnt = 0;

>     mutex avg_lock;

>     void avg_add(int v)
>     {
>         scopelock lock(avg_lock);
>         avg_sum += v;
>         avg_cnt++;
>     }

>     int avg_get()
>     {
>         int result;
>         {
>             scopelock lock(avg_lock);
>             if (avg_cnt == 0)
>                 result = 0;
>             else
>                 result = avg_sum / avg_cnt;
>         }
>         return result;
>     }

Example 2. A multithreaded TCP server that uses the jobqueue class to maintain a thread pool - a fixed list of reusable threads that receive job `assignments' from a queue. The code below can be used as a template for a multithreaded network server.

>     #include <ptypes.h>

>     #include <ptime.h>
>     #include <pasync.h>
>     #include <pinet.h>

>     USING_PTYPES

>     const int testport = 8085;
>     const int maxthreads = 30;
>     const int maxtoken = 4096;

>     const int MSG_MYJOB = MSG_USER + 1;

>     class myjobthread: public thread
>     {
>     protected:
>         int id;
>         jobqueue* jq;
>         virtual void execute();
>     public:
>         myjobthread(int iid, jobqueue* ijq)
>             : thread(false), id(iid), jq(ijq)  {}
>         ~myjobthread()  { waitfor(); }
>     };

>     class myjob: public message
>     {
>     public:
>         ipstream* client;
>         myjob(ipstream* iclient)
>             : message(MSG_MYJOB), client(iclient)  {}
>         ~myjob()  { delete client; }
>     };

>     void myjobthread::execute()
>     {
>         bool quit = false;
>         while (!quit)
>         {
>             // get the next message from the queue
>             message* msg = jq->getmessage();

>             try
>             {
>                 switch (msg->id)
>                 {
>                 case MSG_MYJOB:
>                     {
>                         ipstream* client = ((myjob*)msg)->client;

>                         // read the request line
>                         string req = lowercase(client->line(maxtoken));
>                         if (req == "hello")
>                         {
>                             // send our greeting to the client
>                             client->putline("Hello, " + iptostring(client->get_ip()) + ", nice to see you!");
>                             client->flush();

>                             // log this request
>                             pout.putf("%t  greeting received from %a, handled by thread %d\n",
>                                 now(), long(client->get_ip()), id);
>                         }
>                         client->close();
>                     }
>                     break;

>                 case MSG_QUIT:
>                     // MSG_QUIT is not used in our example
>                     quit = true;
>                     break;
>                 }
>             }
>             catch(exception*)
>             {
>                 // the message object must be freed!
>                 delete msg;
>                 throw;
>             }
>             delete msg;
>         }
>     }

>     void servermain(ipstmserver& svr)
>     {
>         jobqueue jq;
>         tobjlist<myjobthread> threads(true);

>         // create the thread pool
>         int i;
>         for(i = 0; i < maxthreads; i++)
>         {
>             myjobthread* j = new myjobthread(i + 1, &jq);
>             j->start();
>             threads.add(j);
>         }

>         ipstream* client = new ipstream();

>         pout.putf("Ready to answer queries on port %d\n", testport);

>         while(true)
>         {
>             svr.serve(*client);

>             if (client->get_active())
>             {
>                 // post the job to the queue; the client object will be freed
>                 // automatically by the job object
>                 jq.post(new myjob(client));
>                 client = new ipstream();
>             }
>         }
>     }

>     int main()
>     {
>         ipstmserver svr;

>         try
>         {
>             // bind to all local addresses on port 8085
>             svr.bindall(testport);

>             // enter an infinite loop of serving requests
>             servermain(svr);
>         }
>         catch(estream* e)
>         {
>             perr.putf("FATAL: %s\n", pconst(e->get_message()));
>             delete e;
>         }

>         return 0;
>     }

See also: thread, mutex, rwlock, jobqueue, message, Networking examples

PTypes home