473,406 Members | 2,619 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

100% CPU in multithreading applications

Airslash
221 100+
Still struggling with my client & server applications (see previous posts), but right now I've managed to gain a stead 10FPS when transfering images from the server to the client. So i'm making progress.

The problem I'm currently experiencing, is that after a few seconds both my client and server application start claiming 100% of the CPU. I've placed Thread.Sleep() functions in the loops to make sure they're don't claim everything, but it's not helping. Below is the loop function for my 4 threads. Someone who can point out whats causing this?

All Threads rely on the Thread class of .NET as a private member of my components. I've stripped all comments to ensure the code fits. I know some paths in the loops do not enter the sleep, but the logic here says that work needs to be performed. The idea is that the client sends a single request and the server pushes data back untill told to stop.

Parser loop: parses the data received from the tcp socket.
Expand|Select|Wrap|Line Numbers
  1.         void ProcessRoutine()
  2.         {
  3.             m_running = true;
  4.  
  5.             while(m_running)
  6.             {
  7.                 try
  8.                 {
  9.                     if (Buffer.Length > 0)
  10.                     {
  11.                         int start_position = 0;
  12.  
  13.                         while (start_position < Buffer.Length - 4)
  14.                         {
  15.                             string section = Encoding.ASCII.GetString(Buffer.Read(start_position, 4));
  16.  
  17.                             if (string.Equals(section, "@VT:"))
  18.                             {
  19.                                 int binary_size = BitConverter.ToInt32(Buffer.Read(start_position + 8, 4), 0);
  20.  
  21.                                 if ((start_position + 12 + binary_size) <= Buffer.Length)
  22.                                 {
  23.                                     byte[] symbol = Buffer.Read(start_position + 12 + binary_size, 1);
  24.  
  25.                                     if (Encoding.ASCII.GetString(symbol, 0, 1) == "#")
  26.                                     {
  27.                                         int end_position = start_position + 12 + binary_size + 1;
  28.  
  29.                                         IVTMessage message = IVTMessageBuilder.Construct(Buffer.Read(start_position, end_position));
  30.  
  31.                                         Buffer.Delete(start_position, end_position);
  32.  
  33.                                         RaiseOnMessageEvent(message);
  34.  
  35.                                         start_position = 0;
  36.                                         break;
  37.                                     }
  38.                                 }
  39.                                 else
  40.                                 {
  41.                                     Buffer.Delete(start_position, start_position + 12 + binary_size + 1);
  42.                                     start_position = 0;
  43.                                     break;
  44.                                 }
  45.                             }
  46.                             else
  47.                             {
  48.                                 start_position++;
  49.                             }
  50.                         }
  51.                     }
  52.                     else
  53.                     {
  54.                         Thread.Sleep(50);
  55.                     }
  56.                 }
  57.                 catch (ThreadAbortException)
  58.                 { 
  59.                     m_running = false;
  60.                     Debug.WriteLine("Background thread has been aborted.");
  61.                 }
  62.                 catch (Exception ex)
  63.                 { 
  64.                     Debug.WriteLine("   Exception message");
  65.                     Debug.WriteLine("========================");                
  66.                     Debug.WriteLine(ex.Message);
  67.                     Debug.WriteLine(" InnerException message");
  68.                     Debug.WriteLine("========================");
  69.                     Debug.WriteLine(ex.InnerException.Message);
  70.                     Debug.WriteLine("       StackTrace");
  71.                     Debug.WriteLine("========================");
  72.                     Debug.WriteLine(ex.StackTrace);
  73.                 }
  74.             }
  75.         }
  76.  
TCP loop: polls the socket for data
Expand|Select|Wrap|Line Numbers
  1.         void ListenRoutine()
  2.         { 
  3.             m_running = true;
  4.  
  5.             while (m_running)
  6.             {
  7.                 try
  8.                 {
  9.                     if (m_socket != null)
  10.                     {
  11.                         lock (m_lock)
  12.                         {
  13.                             if (Connected && (m_socket.Available > 0))
  14.                             {
  15.                                 int data_available = m_socket.Available;
  16.                                 byte[] buffer = new byte[data_available];
  17.                                 int bytes_read = m_socket.Receive(buffer, 0, data_available, SocketFlags.None);
  18.  
  19.                                 RaiseOnDataEvent(buffer, bytes_read, (m_socket.RemoteEndPoint as IPEndPoint).Address.ToString(), (m_socket.RemoteEndPoint as IPEndPoint).Port);
  20.                             }
  21.                         }
  22.  
  23.                         Thread.Sleep(50);
  24.                     }
  25.                     else
  26.                     {
  27.                         throw new Exception("The internal socket has been closed/disposed.");
  28.                     }
  29.                 }
  30.                 catch (Exception ex)
  31.                 {
  32.                     RaiseOnErrorEvent("ListenRoutine", ex);
  33.                     Disconnect();
  34.                 }
  35.             }
  36.         }
  37.  
I know these are rather difficult things to ask, but I'm a bit clueless as where to look/proceed to find the issue.
Also, code still belongs to me. You can use it if it's usefull, but please put in the source where you got it from.
Sep 30 '10 #1
2 2116
TamusJRoyce
110 100+
The first thing I see is that (start_position + 12 + binary_size) will always be constant. Because of this,

Expand|Select|Wrap|Line Numbers
  1. int binary_size = BitConverter.ToInt32(Buffer.Read(start_position + 8, 4), 0);
  2.  
  3. if ((start_position + 12 + binary_size) <= Buffer.Length)
  4. {
  5.   // Will always be true
  6. } else {
  7.   // Will never be hit
  8.   break; // break loop
  9. } // End if
  10.  
Maybe you want:

Expand|Select|Wrap|Line Numbers
  1. int binary_size = 0;
  2.  
  3. while (m_running)
  4. {
  5.   ...
  6.   binary_size += BitConverter.ToInt32(Buffer.Read(start_position + 8, 4), 0);
  7.  
  8.   if ((start_position + 12 + binary_size) <= Buffer.Length)
  9.   {
  10.     // Will always be true
  11.   } else {
  12.     // Will never be hit
  13.     break; // break loop
  14.   } // End if
  15.  
I think this would cause your client to pull for data endlessly. I'm not sure why your server would spike at 100%, though. Since when it completes sending data, it should wait.

I am guessing, however, that Buffer.Read() returns the number of bytes read, and not the location of the read.
Oct 1 '10 #2
Airslash
221 100+
I sorted it myself, one of the possible logic loops resulted in no Thread.Sleep beeing called, thus keeping the thread hogging all the CPU.

The part with binary_size, is that I read out 4 bytes from the TCP message to determine how many data is still behind. But since I do not know if they're already received I had to do it this way.

The new loop is 3 times shorter and has no CPU load anymore.
Oct 1 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: w3r3w0lf | last post by:
hello! can anyone give me any reference on multithreaded applications in c/c++, BUT in linux... that is, some equivalents on _createthred,_endthread etc.. googling gave everything but a simple...
47
by: mihai | last post by:
What does the standard say about those two? Is any assurance that the use of STL is thread safe? Have a nice day, Mihai.
11
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate...
16
by: Robert Zurer | last post by:
Can anyone suggest the best book or part of a book on this subject. I'm looking for an in-depth treatment with examples in C# TIA Robert Zurer robert@zurer.com
4
by: Edward W. | last post by:
Can you do multi-threading in web applications? I basically understand how to do it in winforms but am not sure about it in web apps. Can someone point me to to an exmaple or an article that...
7
by: noid droid | last post by:
Greetings. I received 4 VB .NET books and looking through the indices and tables of contents, I see that none of them addresses multithreading in VB ..NET. I just bought a bunch of books because...
5
by: Richard Aubin | last post by:
Hello all, I have the following nested loop structure that I would love to convert to x amount of threads: For i = 0 To 100 For j = 0 To 100 For k = 0 To 100 Console.WriteLine("k = " & k)...
55
by: Sam | last post by:
Hi, I have a serious issue using multithreading. A sample application showing my issue can be downloaded here: http://graphicsxp.free.fr/WindowsApplication11.zip The problem is that I need to...
2
by: sergejusz | last post by:
Hi all, Please take a look at simple set of VB.NET classes to develop "boss-workers"- style multithreading applications. Maybe it will help somebody: http://www.sergejusz.com/boss_workers.htm ...
2
by: Pradnya Patil | last post by:
hi , I am trying to draw ' html div-tag ' on the screen which will resemble a rectangle through vb.net code. I want it to be drawn faster...so I introduced multithreading using Threadpool. I...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.