views:

130

answers:

3

SO users,

I have 3 threads running simultaneously at any given time, trouble is after thread 1 tries to connect to a server by passing a username to it thread 2 is being invoked and by the time its thread 1's turn the server closes its connection on the code.

Is there anywhere I can implement sending username and password simultaneously with out threads interrupting each other at this time?

Thx!, Nidhi

+4  A: 

I very much doubt that it's genuinely thread contention which is the problem here.

Threads timeslice very quickly, and the server would have to have a ridiculously short timeout for your diagnosis to be correct.

My guess is there's something different wrong with your code, but we can't really tell what it is without seeing some code.

Jon Skeet
Although your answer didn't solve my problem, but your article on multithreading did - http://www.yoda.arachsys.com/csharp/threads/locking.shtml Thanks!
Nidhi
Can you say how you solved the problem?
John Saunders
Yes, even I would like to know how the problem was solved.
P.K
+1  A: 

threads typically swap on the order of milliseconds, so i don't think thats whats causing your program to disconnect.

That said, you can implement locks/mutexes to ensure that critical code is executed without other threads executing their code, and even use thread prioritization to ensure one thread gets priority over others - but you cannot force a thread not to yield, the operating system can decide you've run long enough and force you to yield regardless. Besides, the behavior your looking for is more or less explicitly prevented in all modern schedules to prevent starvation of other processes.

cyberconte
+1  A: 

It looks like you're trying to multiplex multiple data streams on one socket. So you may be running into a thread switching problem while waiting for the server, but if that's the case you're probably doing something like this, which is an inappropriate way to multithread.

void Task(int type)
{
  // Authenticate
  // Send Data
  // Disconnect
}

// Connect
Thread.Start(Task(1));
Thread.Start(Task(2));
Thread.Start(Task(3));

If you've got threads 1, 2, and 3 doing work on the server in tandem you've got a few ways to do it:

1.) Do your work threaded with different connections

void Task(int type)
{
  // Connect
  // Authenticate
  // Send Data
  // Disconnect
}

Thread.Start(Task(1));
Thread.Start(Task(2));
Thread.Start(Task(3));

2.) Do your work singlethreaded with one connection

void Task(int type) { // Send Data }

// Connect // Authenticate Task(1); Task(2); Task(3); // Disconnect

3.) Use multiple connections

Hounshell