Write a file in WindowsProgramA process fork generates about 2000 threads and then exits abnormally. Why?
This problem occurs because in Windows 32-bit system, a process can use a maximum of 2 GB of virtual memory, and the default thread stack stacksize of a thread is 1024 K (1 m ), in this way, when the number of threads approaches 2000, 2000*1024 K = 2G (approximately), memory resources are equivalent to depletion.
Msdn Original:
"The number of threads a process can create is limited by the available virtual memory. By default, every thread has one megabyte of stack space. Therefore, you can create at most 2,028 threads.If you reduce the default stack size, you can create more threads.However, your application will have better performance if you create one thread per processor and build queues of requests for which the application maintains the context information. A thread wocould process all requests in a queue before processing requests in the next queue."
How can we break through the 2000 limits?
You can reduce the stack stacksize by modifying the createthread parameter. For example
# DefineMax_threads 50000
DWORD winapi threadproc (lpvoid lpparam ){
While(1 ){
Sleep (100000 );
}
Return0;
}
IntMain (){
DWORD dwthreadid [max_threads];
Handle hthread [[max_threads];
For(IntI = 0; I <max_threads; ++ I)
{
Hthread [I] = createthread (0, 64, threadproc, 0, stack_size_param_is_a_reservation, & dwthreadid [I]);
If(0 = hthread [I])
{
Dword e = getlasterror ();
Printf ("% D \ r \ n", E );
Break;
}
}
Threadproc (0 );
}
Server programming
If your server program is designed to create a thread for a client connection request, there will be 2000 limits (when the number of Hardware Memory and CPU is fixed ). The suggestions are as follows:
The "one thread per client" model is well-known not to scale beyond a dozen clients or so. if you're going to be handling more than that has clients simultaneously, you should move to a model where instead of dedicating a thread to a client, you instead allocate an object. (someday I'll muse on the duality between threads and objects .) windows provides I/O Completion Ports andThread PoolTo help you convert from a thread-based model to a work-item-based model.
1. Serve serving clients with each thread, and use nonblocking I/O and
Level-triggered Readiness notification2. serve serving clients with each thread, and use nonblocking I/O and readiness
Change Icationication3. serve your clients with each server thread, and use asynchronous I/O