server and client threads

I wanted to ping the group and see if anyone else has any input on how 
to handle the following.

I have a server thread which starts a new background thread when a 
connection is accepted on a socket.

What I want to understand is what is the best way to track the spawned 
threads so that when the user goes to shutdown the application, we know 
how many active child connections are running and we can terminate them 
prior to the application being stopped.

TIA
Chris
0
2/3/2005 5:44:57 PM
vc.mfc 33608 articles. 0 followers. Follow

2 Replies
541 Views

Similar Articles

[PageSpeed] 0

On Thu, 03 Feb 2005 12:44:57 -0500, chris cranford
<chris.cranford@tkdsoftware.com> wrote:

>I wanted to ping the group and see if anyone else has any input on how 
>to handle the following.
>
>I have a server thread which starts a new background thread when a 
>connection is accepted on a socket.
>
>What I want to understand is what is the best way to track the spawned 
>threads so that when the user goes to shutdown the application, we know 
>how many active child connections are running and we can terminate them 
>prior to the application being stopped.
>
>TIA
>Chris

The server just keeps a list of threads that it spawns.  Then when it
is time to shut down, the server can signal each thread in an
appropriate way (message, event, etc) that it should close down in an
orderly way.  Given the list of threads (handles or other identifier),
you can also forcibly shut down any spawned thread that doesn't
respond properly to the shutdown request.




0
r
2/3/2005 6:07:50 PM
In article <wcNNTP.01c50a18.410fbb10.1000.0@tkdsoftware.com>, 
chris.cranford@tkdsoftware.com says...
> I wanted to ping the group and see if anyone else has any input on how 
> to handle the following.
> 
> I have a server thread which starts a new background thread when a 
> connection is accepted on a socket.

Sure: handle it by not doing that.

I've seen lots of people build things this way, and I've yet to see 
it turn out well. It's too much work for a server that will be used 
only lightly, and if the server is used heavily, it creates so many 
threads they bring the server to its knees in no time. Systems like 
this are particularly prone to DoS attacks.

At least from what I've seen, it generally works out better if you 
start by creating a queue to transmit data from one thread to the 
others. You then spin up some fixed number of threads, and have them 
all wait on the queue, so one will wake up anytime there's an item in 
the queue.

When it's time to shut down the server, you put pseudo-tasks in the 
queue that tell the threads to terminate (as many tasks as you 
created threads). The main thread then waits on an array of handles 
to the child threads until they're all signaled, indicating they've 
all terminated so it's safe for the parent thread to terminate as 
well.

So the main thread looks like this:

// warning: untested C-like pseudo-code.
const int thread_count = 8; // arbitrarily chosen # of threads.
HANDLE threads[thread_count];	

// create the threads
for (int i=0; i<thread_count; i++)
	threads[i] = CreateThread(/* ... */);

// process connections
while (!terminate) { 
	gather_connection_info(&data);
	queue.add(new conn_data(data));
}

// kill child threads
static conn_data term = { terminate };
for (int i=0; i<thread_count; i++)
	queue.add(&term);

// wait 'til they're gone. Consider limiting the time in case
// a thread has crashed.
WaitForMultipleObjects(8, threads, true, INFINITE);

and each thread looks roughly like this:

conn_data *data;
while (!is_exit_msg(data=queue.get())) {
	process_connection(data);
	delete data;
}

This has the advantage that most of the thread synchronization 
"stuff" ends up in the code for the queue, where it's easy to re-use 
for quite a variety of different multi-threaded processes:

// Non-warning: real, more-or-less trusted code.
#include <windows.h>

template<class T, unsigned max = 256>
class queue { 
    HANDLE empty;	// count of empty slots
    HANDLE full;	// count of full slots
    CRITICAL_SECTION mutex;	// protect buffer, in_pos, out_pos
    
    T buffer[max];
    long in_pos, out_pos;
public:
    queue() : in_pos(0), out_pos(0) { 
        empty = CreateSemaphore(NULL, max, max, NULL);
        full = CreateSemaphore(NULL, 0, max, NULL);
        InitializeCriticalSection(&mutex);
    }

    void add(T data) { 
        WaitForSingleObject(empty, INFINITE);       
        EnterCriticalSection(&mutex);
        buffer[in_pos] = data;
        in_pos = (in_pos + 1) % max;
        LeaveCriticalSection(&mutex);
        ReleaseSemaphore(full, 1, NULL);
    }
        
    T pop() { 
        WaitForSingleObject(full,INFINITE);
        EnterCriticalSection(&mutex);
        T retval = buffer[out_pos];
        out_pos = (out_pos + 1) % max;
        LeaveCriticalSection(&mutex);
        ReleaseSemaphore(empty, 1, NULL);
        return retval;
    }
  
    ~queue() { 
        CloseHandle(empty);
        CloseHandle(full);
        DeleteCriticalSection(&mutex);
    }
};

In case you want to test that out on something innocuous before 
putting it into a real program, here's a short bit of test code:

#ifdef TEST 

#include <iostream>
#include <process.h>

void process(void *p) { 
    queue<int> &q = *static_cast<queue<int> *>(p);

    int val;
    while ( -1 != (val=q.pop()))
        std::cout << val << std::endl;
}

int main() { 
    queue<int> things;
    enum { thread_count = 4 };
    HANDLE threads[thread_count];
    
    for (int t=0; t<thread_count; ++t)
        threads[t]=(HANDLE)_beginthread(process, 0, &things);

    for (int i=0; i<20; ++i)
        things.add(i);

    for (int j=0; j<thread_count; ++j)
        things.add(-1);

    WaitForMultipleObjects(thread_count, threads, TRUE, INFINITE);

    return 0;
}

#endif

One question that regularly comes up with thread pools is how many 
threads to create. The answer varies with what you're doing and the 
number of processors in the system. The basic idea is to use as few 
threads as necessary so that when one thread stalls, there will be 
another waiting to run. Unless you're truly masochistic, you'll also 
want to set 64 as a hard upper limit, as that's the most you can wait 
for with WaitForMultipleObjects at one time.

Fortunately, it rarely matters a lot, and a simple of thumb like 
twice as many threads as processors in the system is usually a decent 
starting point, and it's often easiest to just experiment from there.

Now aren't you glad you only asked a short, simple question? 
Otherwise the answer would've looked like an encyclopedia! :-)

-- 
    Later,
    Jerry.

The universe is a figment of its own imagination.
0
jcoffin1 (194)
2/5/2005 8:46:46 AM
Reply:

Similar Artilces:

NO DEFAULT SMTP SERVER..
Hello, I had a problem with exadmin.dll, unregistered it, copied new one and registered it and now the default smtp server is gone under SMTP in my systems manager but everything still works.... HELP where is it ? and how can i get it back ? tnnx. Philippe ...

Upgrading from server 2000 to server 2008R2?
We would like to upgrade our servers to Windows server 2008 R2. Currently we have two Windows 2000 (SP 4) domain controllers, we want to replace the Forest Root Domain box with new hardware & upgrade the other DC to server 2008 R2. I understand it's not possible to upgrade from 2000 straight to 2008 but is server 2003 still available to ugrade to in between? I'm also not sure of what the implications of retiring the Forest Root Domain box would be? Would the best plan be to add the new 2008 server (domain function & forest function level: 2000); upgrade the se...

Need help solving a threading issue
Hi folks, I have an MFC application that has some GUI functionality. It's main thead creates a worker thread (using AfxBeginThread), and this worker thread needs to create an instance of a class (which we'll call 'network' for now) which does some TCP/IP networking stuff; functionality achieved by inheriting from another class. Also, The 'network' class and the main thead talk to each other via PostMessage. Now my problem is that I can't figure out how to instantiate the network class to get everything to work. Here's my attempts and resultant failures: AT...

Outlook client to Exchange encryption enforcement
I have a client that requires encryption between thier Outlook clients and Exchange server. Can a registry key or application setting be used to enforce Outlook to Exchange encryption? If so what is the encryption used? I am aware of RPC-over-HTTPS and can and will deploy if necessary that as well but what I need is an enforcement of such a policy. I have set the Outlook 2003 option "Encrypt data between Microsoft Office Outlook and Microsoft Exchange Server " Any ideas or suggestions are much appreciated! -MJB I think you could certainly configure client access to go o...

Can Recovery Storage Groups be used if original server gone?
We had an Exchange server die on us a few months back due to hardware issues. All accounts were moved to another box and that one was flattened and taken out of the Exchange org. It was replaced by new hardware that does NOT have the storage groups or databases that the old one did. We have a request to recover data from an info store back up prior to the events above and are running into problems with our backup vendor. Would it be possible to use a Recovery Storage Group to retrieve this data? The mailbox still exists (but may have been moved via Exmerge) so I believe I will pas...

MS Project Server Admin // Denver, CO
MS Project Server Admin Location: Denver, CO Duration: 6 months Pay Rate: DOE =95 MSProject Server ver 2010, SQL database and Sharepoint 2010 =95 Ongoing support and maintenance involving activities such as =96 Monitoring logs, Patches, resolving support tickets, Dev/Test/Prod support =95 Routine troubleshooting =95 Technical APS maintenance (Project Server & SharePoint 2010) =95 User administration / Password resets etc. =95 Work with Microsoft for any critical issues that might need intervention from Microsoft =95 Application of Patches & migration to Production =95 SQL services mo...

Small Business Server in Windows Server 2000 Environment
I have a requirement to install Microsoft CRM for about 10 CRM Users. The existing Windows 2000 has about 120 users with two Exchange Servers. Is it possible to set up a separate Small Business Server to run CRM within the Windows 2000 domain as this is the most cost effective way of implementing CRM for such a low User count? ...

Removed server, exchange still looking for it?
Exchange 5.5, I removed a server from the site using exchange admin, and now am getting event 9318, saying MTA can't contact it. Why is it doing that? I had the same problem after a 5.5 to 2000 migration. Rebooting the Exchange server that was trying to connect resolved the problem. MTA must keep the information cached. Tim "dlw" <dlw@discussions.microsoft.com> wrote in message news:C431500C-F78D-47E5-AAC5-B8C611592E97@microsoft.com... > Exchange 5.5, I removed a server from the site using exchange admin, and > now > am getting event 9318, saying MTA can...

Sales for Outlook 1.2 Client Install Errors
We have been experiencing some problems reinstalling the Outlook Sales client on a machine that lost functionality with the CRM Appointment button. The form just stopped loading when the button was clicked, so we followed the following steps: 1. We removed and then re-added the COM object Microsoft CRM Outlook Addin and also cleared the forms cache in Forms Manager. This did not resolve the issue. 2. We then completely uninstalled Sales for Outlook 1.2, rebooted the system, reinstalled and rebooted and when Outlook was launched, it now delivers the error "An error occurred in...

windows 2008 server cord and windows 2008 std
we have 20+ New server to install windows 2008 for trading purpose. still can not decide to install server core or std full, can someone advise what is the benefit to install core rather than std edition or to install std edition ? DD, There is: Server Standard Server Standard Core Server Enterprise Server Enterprise Core Core is (not quite correctly called) 'Server without Graphical User Interface (GUI)'. There are several reasons why Core was introduced: - *Nix purists were saying that there's no real need/use for GUI on a server and *real* sysadmins ar...

Outlook won't leave messages on the server
I have tried and tried to keep Outlook 2003 from deleting my email off my server. I have found the check box under advanced send\receive setting in "options" and I have tried variations of the 3 check boxes in this window and they work until I close Outlook and reopen it, then all of my settings return to the default of deleting my email off the server. Wasn't MS suppose to stop doing things like this? Any help in steering me to the answer (which i am sure is here) to this question is appreciated. Regards Paul A. Walters Hi, Goto Tools --> Email Accounts --> V...

Project Server Provisioned
Hello, I have provisioned Project Server and added it to the trusted zone, but it still comes up unresolved. Hello, You mean PWA home page is not loading or issue with connecting from MS Project Professional? Also mention the version of Project Server. Thanks Chak pVector Technologies http://www.pvectortech.com http://www.epmcentral.com On Apr 16, 11:04=A0am, me <mtyso...@yahoo.com> wrote: > Hello, I have provisioned Project Server and added it to the trusted > zone, but it still comes up unresolved. On Apr 16, 12:20=A0pm, Chak <chak...@hotmail.com>...

OT: SVN server
Hi, Sorry for the OT, I am not 100% sure where to ask. I want to setup a subversion repo on a personal website. Would anyone know the best forum/NG to ask such a question? (Or where I could find a tutorial for installing such a repo). Thanks Simon Simon wrote: > Hi, > > Sorry for the OT, I am not 100% sure where to ask. > > I want to setup a subversion repo on a personal website. > Would anyone know the best forum/NG to ask such a question? > (Or where I could find a tutorial for installing such a repo). > > Thanks > > Simon ...

Windows Server 2008 RC2 in Windows Server 2003 Domain
I'm having trouble with one domain controller that has all of the FSMO roles (I have 6 Domain controllers in total running server 2003) I updated my schema to version 47 (Windows server 2008 RC2) and would like to add a new physical server with W2K8 R2 on it and transfer all of the FSMO roles on it. I don't want to upgrade all DC's yet to 2008 R2 yet, so the domain functional level will stay the same for a while (Windows Server 2003). Is there anything I should watch out for with this scenario? Or by just adding a W2k8 R2 box with all the FSMO roles and then decomm...

Exchange Router setup/Setting More than one Exchange Server up in one organisation with two active directories?
Forgive the version difference, but on Exchange 2003 is there a way to install a secondary Exchange Server on a different domain and somehow have it routed to from the other domain or act as a connector to be able to see those emails without removing them? I don't know enough about routing on Exchange to figure if its capable. Or perhaps I need to utilise a different registered email domain and I should use this for testing instead of trying to somehow route emails from one to the other? eg instead of companyname.com I could use companynamecrm.com or something. Would I still want to setu...

pop3 server response
When opening outlook recently it has been saying my pop3 server hasn't respoded in 60 seconds and asks if I would like to wait longer for the server to respond. but sometimes it goes right through. is there any reason why this might be happening. i can only get e-mail about 60% of the time. any help would be greatly appreciated. J.H. Try removing and reinstalling your mail account settings. --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. Due to the Swen virus, all e-mails sent to my actual account will be deleted w/out reading. After...

Manually run message rules on the server
Hi, Is there a way to run message rules (created by the end-user on Outlook) on the server, say on a daily basis ? The reason is that that person has ~50 rules, moving all incoming messages from his inbox to specific folders. Since he now owns a BES-enabled BlackBerry, these rules prevent him from getting his emails onto his handheld. The idea would be to run all the rules once a day, on his behalf, on the server. Exchange 2007 SP1 Thanks Christian Some rules, like moving messages to another folder in the same mailbox, will run server-side by default, depending on how they're create...

E-Mail Messages Reappear When Server is rebooted
Hello All, I had reason to reboot a windows2003 SBS a few months ago. When it rebooted clients reported old emails had reappeared in their inbox. I was then on a windows2000 SBS site yesterday and when I rebooted the server old emails reappeared. The Windows2003 server rebooted today and again old email reappear. I cannot find any info on web re: this problem. Any help would be appreciated. Sam wrote: > Hello All, > > I had reason to reboot a windows2003 SBS a few months ago. When it > rebooted clients reported old emails had reappeared in their inbox. I > was then on...

web server and exchange server on 2 different servers.
Is there a way to redirect traffic through my web server to my mail server to use OWA with out setting up a front end/back end? If I do have to set up a front end do I have to purchase a separate license? What version of Exchange? If E2k/2003, you have to use FE/BE....and for E2k, the FE server has to be Enterprise. Gonzosez wrote: > Is there a way to redirect traffic through my web server to my mail > server to use OWA with out setting up a front end/back end? > > If I do have to set up a front end do I have to purchase a separate > license? You can install OWA on the w...

MultiFunctional Printers and Server 2008
Hello is there are a way without using TS Server to use a printer that is off location? -- Member - Liberal International This is doctor@nl2k.ab.ca Ici doctor@nl2k.ab.ca God, Queen and country! Never Satan President Republic! Beware AntiChrist rising! http://twitter.com/rootnl2k http://www.facebook.com/dyadallee UK Time for a Common Sense change vote Liberal Democrat / Alliance Yes, there are many ways. You can use print server device, like HP JetDirect. You can attach printer to any networked computer. "The Doctor" <doctor@doctor.nl2k.ab.ca> wrote in message ...

Importing XML data into SQL Server 2005
Hi, We have an app in .NET with sql server 2005 backend and would need to import relatively huge amount of data from disparate providers on a nightly basis. What is the file format that is preferred and please help me understand why we need to go with a specific format? Is it XML, CSV, or anything else? We have been leaning towards using XML If it is XML, how can we a template for the XML file (is it the XSD schema file?) and pass it to the providers so that we can get formatted data without much discrepancies? Thanks in advance! ...

If NIC teaming good or bad for Exch2003 server?
Hi there, For exchange2003 server running on branded server hardware such as HP, if network card teaming (of 2 nics) a good option for exchange2003 or not? How do you guys doing? Just using 1 nic or what? Many thanks! Leemutpo - The good thing about HP is that it will present one virtual NIC to the OS. Generally, unless my client has good network hardware with relatively current IOS levels and good network and server support teams, I will try to steer them clear of NIC teaming. Granted, it is good for redundancy. However, it does have the occasional problem, depe...

Exchange Attributes Missing for New Users after Server Move
Hi, We have recently migrated our Exchange 2003 Enterprise Server by installing the new server on a new platform with a new name in the domain, then used the Move Mailboxes feature. I then followed the procedures in http://support.microsoft.com/kb/822931/ How to remove the first Exchange Server 2003 computer from the administrative group. I shut down the old server and left if configured for December. I have just disposed of the original server (Generation 1 Compaq Proliant). However we have a new user starting today, and although AD seems to add his account as usual, there is no Exchange a...

Multiple Service Failures Exchange Server 2003 Win2K3
My Exchange Server has freaked out tonight, and now into the morning I'm still scratching my head. The IISAdmin, Microsoft Exchange Routing Engine & SMTP Protocol Service keep giving the following errors: IISAdmin - 7031 The IIS Admin Service service terminated unexpectedly. It has done this 29 time(s). The following corrective action will be taken in 1 milliseconds: Run the configured recovery program. Microsoft Exchange Routing Engine - 7034 The Microsoft Exchange Routing Engine service terminated unexpectedly. It has done this 29 time(s). Simple Mail Transport Proto...

application closing in windows 2000 server
hi, I compliled and run the chat server(got the source from MSDN) in the Windows 2000 server(No service pack). I compiled and copied the chat client in another machine(windows 98). When i run the client, it asked the handle and chat server. I gave my name as handle and chat server machine name as server. Then i click on the OK button, the chat server application got closed with out giving any error message. In client i got the message "Failed to connect server Try Again?". Then i copied the same server application to the windows 98 machine and run the chat server applicatio...