Threading issue

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I've written a component which will be used by client and server
applications. The component uses TCP to send structures to a destination
socket. When sending, each structure is serialized contains a header
specifying what type of object it is and its purpose. The receiving section
of the component has to deserialize the header section of the received data
and decode what object it is, and then it has to send an ACK structure to the
sender to confirm the reception.

I wrote a testserver application and a testclient application which both use
the component. To test, i have 10 clients connect to the server and they
basically play "packet tennis", i.e. they throw a packet back and forth to
each other. Now, the problem i am having occurs in the receiving section of
the component. When TCP receives data, i call a method named Data_Rec() which
deserializes the header and decodes it. It then starts a new thread (created
manually) which handles what the received packet asks for. The problem i had
to solve here was how to pass the header parameters to the newly spawned
thread. I couldn't use global variables because Data_Rec() returns from the
main thread and recevies more data thereby overwriting the global vars.

My first implementation involved creating a class called ThreadProcParam
which contained fields that will hold the parameters. So when im about to
spawn the thread, i instantiate a ThreadProcParam obj and initialize it using
the parameters i want to pass to the thread. I then add this obj to a global
queue. Once the thread is spawned, it dequeues the queue and obtains the
parameters as required.

Running the testserver with 1 client works fine. When i run this server
handling 10 connected clients, the system works for a while but at a random
point in time any one of the clients may receive a corrupt structure. It
seems that the parameters of a current structure had been overwritten by
another incoming structure... or something like that, im not even sure... but
i thought my implementation was rather robust - each thread spawned is
separated from each other - apparently not.

I then tried another approach by using the ThreadPool and passing the
parameters when calling QueueUserWorkItem. This worked like a charm but it
seemed rather slower. What would be the best approach when passig parameters
to a thread? Is my implementation appropriate? Is there a better way? Thanks.

Michael--J.
 
Back
Top