Difference between revisions of "Threads"

From Valve Developer Community
Jump to: navigation, search
Line 7: Line 7:
 
Threads in Source are child classes of <code>CWorkerThread</code>. These contain a number of variables, a calling command, and the mainloop <code>int Run()</code>. An instance of the class is declared inside a source file. The other threads can call this thread by calling the proper functions in this instance. The thread is not nessesarily running when these functions are executed and will most likely be required to be started prior to any calls. A sample thread with a single function would look like this.
 
Threads in Source are child classes of <code>CWorkerThread</code>. These contain a number of variables, a calling command, and the mainloop <code>int Run()</code>. An instance of the class is declared inside a source file. The other threads can call this thread by calling the proper functions in this instance. The thread is not nessesarily running when these functions are executed and will most likely be required to be started prior to any calls. A sample thread with a single function would look like this.
  
 +
{{note|All code in this article is only tested in client.dll and a radically different approach might be used in server.dll.}}
 
<pre>
 
<pre>
 
//-----------------------------------------------------------------------------
 
//-----------------------------------------------------------------------------
// A thread for async PingBack'ing.
+
// A thread that can execute a function asynchronously.
 
//-----------------------------------------------------------------------------
 
//-----------------------------------------------------------------------------
 
class CMyAsyncThread: public CWorkerThread  
 
class CMyAsyncThread: public CWorkerThread  
Line 38: Line 39:
 
  m_Parameter = Parameter;
 
  m_Parameter = Parameter;
 
  CallWorker( CALL_FUNC );
 
  CallWorker( CALL_FUNC );
  Assert( !Parameter1);
+
 
  Assert( !Parameter2 );
 
 
  return true;
 
  return true;
 
  }
 
  }
Line 73: Line 73:
  
 
static CMyAsyncThread g_CMyAsyncThread;
 
static CMyAsyncThread g_CMyAsyncThread;
 +
</pre>
 +
 +
This sample will now be explained in details. However parts of the following might not be confirmed and is based on guesses and experience.
 +
 +
A thread is declared as a child class of CWorkerThread. The constructor sets the name of the thread. The official Valve Threads the name of the class without the leading C, but in theory this value could be anything. In the constructor all parameters should be initalized to zero, avoiding any nasty situations where they could by accident be initalized to something else. The destructor is defined and should be used to clean up, but with thread safety in mind.
 +
<pre>
 +
class CMyAsyncThread: public CWorkerThread
 +
{
 +
public:
 +
  CAsyncPingBackThread() :
 +
  m_Parameter1( NULL ) ,
 +
  m_Parameter2( NULL )
 +
  {
 +
  SetName( "MyAsyncThread" );
 +
  }
 +
 +
  ~CAsyncPingBackThread()
 +
  {
 +
  }
 +
</pre>
 +
Like most programs written for Win32, the thread waits for messages before executing code. For simplicity these functions could be written from within a enum. The values of these constants do not matter, as long they're not equal. It is recommended to have an EXIT command in case you wish to shut down the thread, which is nessesary to avoid memory leaks, when the game closes.
 +
<pre>
 +
  enum
 +
  {
 +
  CALL_FUNC,
 +
  EXIT,
 +
  };
 +
</pre>
 +
When you wish to run a certain function in a thread, you can send a message to the thread's main loop. You can in addition copy memory to variables declared within the class, which apparently seems to be shared with the thread, or transmitted. The details of this remains unknown but experience shows that all memory copied to these variables is available when running from within the custom thread. Valve tests the pointers sent to the threads, so we left the code here.
 +
<pre>
 +
  bool CallThreadFunction( char* Parameter1, char* Parameter2 )
 +
  {
 +
  Assert( !Parameter1);
 +
  Assert( !Parameter2 );
 +
  m_Function = Function;
 +
  m_Parameter = Parameter;
 +
  CallWorker( CALL_FUNC );
 +
 +
  return true;
 +
  }
 
</pre>
 
</pre>
  

Revision as of 16:44, 11 December 2008

Modern computers utilize multiple processors and recently games have begun to take advantage from this. By splitting code into multiple threads, it's possible to run code simutaniously on multiple processors. Threads are a very important part of Windows, where most programs use bunches of threads. Please note that the number of threads available is not limited by the number of CPUs, but by the memory in windows. Each thread will by default have a stack size of one megabyte, therefore Win 32 has a limitation of 2048 threads. This article is not about threads in general, but about threads in Source, and assumes you already know how threads work. For more information on how threads work in Windows please read about it on another site.

Source utilizes threads by putting each kind of operation into its own thread. Source has for instance a thread for physics, a thread for AI, a thread for rendering, and so on. If the computer does not have multiple CPUs, it will run every thread on the same CPU and switch between them every few miliseconds. Programmers using the Source SDK can use threads as well by using Valve's classes, and can run important functions, with a lot of waiting, asynchronously. These functions could for instance be WinSock operations, disk read/writes or similar. Functions that just need to wait for a while and then run some code would be better off being implemented by using the SetThink functions.

Threads in Source

Threads in Source are child classes of CWorkerThread. These contain a number of variables, a calling command, and the mainloop int Run(). An instance of the class is declared inside a source file. The other threads can call this thread by calling the proper functions in this instance. The thread is not nessesarily running when these functions are executed and will most likely be required to be started prior to any calls. A sample thread with a single function would look like this.

Note.png Note: All code in this article is only tested in client.dll and a radically different approach might be used in server.dll.
	//-----------------------------------------------------------------------------
	// A thread that can execute a function asynchronously.
	//-----------------------------------------------------------------------------
	class CMyAsyncThread: public CWorkerThread 
	{
	public:
		  CAsyncPingBackThread() :
		  m_Parameter1( NULL ) ,
		  m_Parameter2( NULL )
		  {
			  SetName( "MyAsyncThread" );
		  }

		  ~CAsyncPingBackThread()
		  {
		  }

		  enum
		  {
			  CALL_FUNC,
			  EXIT,
		  };

		  bool	CallThreadFunction( char* Parameter1, char* Parameter2 )
		  {
			  Assert( !Parameter1);
			  Assert( !Parameter2 );
			  m_Function = Function;
			  m_Parameter = Parameter;
			  CallWorker( CALL_FUNC );

			  return true;
		  }

		  int Run()
		  {
			  unsigned nCall;
			  while ( WaitForCall( &nCall ) )
			  {
				  if ( nCall == EXIT )
				  {
					  Reply( 1 );
					  break;
				  }

				  // Reset some variables
				  char* Parameter1 = m_Parameter2;
				  char* Parameter2 = m_Parameter1;				
				  m_Parameter1 = 0;
				  m_Parameter2 = 0;

				  Reply( 1 );
				  FunctionToBeRunFromInsideTheThread(Parameter1,Parameter2);

			  }
			  return 0;
		  }

	private:
		char* m_Parameter1;
		char* m_Parameter2;
	};

	static CMyAsyncThread g_CMyAsyncThread;

This sample will now be explained in details. However parts of the following might not be confirmed and is based on guesses and experience.

A thread is declared as a child class of CWorkerThread. The constructor sets the name of the thread. The official Valve Threads the name of the class without the leading C, but in theory this value could be anything. In the constructor all parameters should be initalized to zero, avoiding any nasty situations where they could by accident be initalized to something else. The destructor is defined and should be used to clean up, but with thread safety in mind.

	class CMyAsyncThread: public CWorkerThread 
	{
	public:
		  CAsyncPingBackThread() :
		  m_Parameter1( NULL ) ,
		  m_Parameter2( NULL )
		  {
			  SetName( "MyAsyncThread" );
		  }

		  ~CAsyncPingBackThread()
		  {
		  }

Like most programs written for Win32, the thread waits for messages before executing code. For simplicity these functions could be written from within a enum. The values of these constants do not matter, as long they're not equal. It is recommended to have an EXIT command in case you wish to shut down the thread, which is nessesary to avoid memory leaks, when the game closes.

		  enum
		  {
			  CALL_FUNC,
			  EXIT,
		  };

When you wish to run a certain function in a thread, you can send a message to the thread's main loop. You can in addition copy memory to variables declared within the class, which apparently seems to be shared with the thread, or transmitted. The details of this remains unknown but experience shows that all memory copied to these variables is available when running from within the custom thread. Valve tests the pointers sent to the threads, so we left the code here.

		  bool	CallThreadFunction( char* Parameter1, char* Parameter2 )
		  {
			  Assert( !Parameter1);
			  Assert( !Parameter2 );
			  m_Function = Function;
			  m_Parameter = Parameter;
			  CallWorker( CALL_FUNC );

			  return true;
		  }
	// Connects to the content servers and executes a function there with a given parameter
	// Runs the code in this thread, so the game will hang until done. Avoid this by using PingBack() instead.
	bool	PingBackThreaded( char* Function, char* Parameter )
	{

	}

	//-----------------------------------------------------------------------------
	// A thread for async PingBack'ing.
	//-----------------------------------------------------------------------------
	class CAsyncPingBackThread : public CWorkerThread 
	{
	public:
		  CAsyncPingBackThread() :
		  m_Function( NULL ) ,
		  m_Parameter( NULL )
		  {
			  SetName( "AsyncPingBackThread" );
		  }

		  ~CAsyncPingBackThread()
		  {
		  }

		  enum
		  {
			  CALL_FUNC,
			  EXIT,
		  };

		  bool	PingBack( char* Function, char* Parameter )
		  {
			  Assert( !Function );
			  Assert( !Parameter );
			  m_Function = Function;
			  m_Parameter = Parameter;
			  CallWorker( CALL_FUNC );
			  Assert( !Function );
			  Assert( !Parameter );
			  return true;
		  }

		  int Run()
		  {
			  unsigned nCall;
			  while ( WaitForCall( &nCall ) )
			  {
				  if ( nCall == EXIT )
				  {
					  Reply( 1 );
					  break;
				  }

				  if (!m_Function)
				  {
					  IngameError("MaxsiDistribution::CAsyncPingBackThread::Run() does not have m_Function set!");
					  m_Function = 0;
					  m_Parameter = 0;			
					  Reply( 0 );
					  return 0;
				  }

				  if (!m_Parameter)
				  {
					  IngameError("MaxsiDistribution::CAsyncPingBackThread::Run() does not have m_Parameter set!");
					  m_Function = 0;
					  m_Parameter = 0;					 
					  Reply( 0 );
					  return 0;
				  }

				  // Reset some variables
				  char* Function = m_Function;
				  char* Parameter = m_Parameter;				
				  m_Function = 0;
				  m_Parameter = 0;

				  Reply( 1 );
				  MaxsiDistribution::PingBackThreaded(Function,Parameter);

				  // Clean up
				  delete[] Function;
				  delete[] Parameter;
			  }
			  return 0;
		  }

	private:
		char* m_Function;
		char* m_Parameter;
	};

	static CAsyncPingBackThread g_AsyncPingBackThread;


	// Creates the thread, from there calls the pingback and then does fancy stuff.
	bool	PingBack( char* Function, char* Parameter )
	{		
		if ( !g_AsyncPingBackThread.IsAlive() )
		{
			g_AsyncPingBackThread.Start();
		}
		if ( !g_AsyncPingBackThread.IsAlive() )
		{
			Warning(":PingBack() failed to start the async pingback thread!");
		}

		// Make some local copies! (Because the real ones COULD get deleted or changed while we upload)
		char* NewFunction	=	BuildString(1,Function);
		char* NewParameter	=	BuildString(1,Parameter);
		
		g_AsyncPingBackThread.PingBack ( NewFunction, NewParameter);

		g_AsyncPingBackThread.CallWorker( CAsyncPingBackThread::EXIT );
		return true;
	}