C # in the Unity game development of multithreaded programming method _c# Tutorial

Source: Internet
Author: User
Tags terminates thread class types of functions

Before that, a lot of people questioned Unity support does not support multithreading, in fact, unity is supporting multiple threads. When it comes to multithreading, we should mention unity, which is very commonly used, but it is not a real multithreaded process. The coprocessor actually waits for an operation to complete before executing the following code, or the control code executes at a specific time. and multithreading in unity rendering and complex logic operations can be efficient use of multi-core CPUs, help programs can be more efficient operation. This article mainly describes how to use multithreading in unity.

First introduce the class library using multithreading in C #

Using System.Threading;

Four ways to create a thread instance

One, the thread executes the parameter-free method

Construct syntax

Initializes a new instance of the Thread class.
//< param name= "start" > No parameter Delegate object. </param> public
Thread (ThreadStart start)

Start

Type: System.Threading.ThreadStart
Represents the ThreadStart delegate for the method to invoke when this thread is started.

void Start ()
{
 //Create a parameterless thread object thread
 THR = new Thread (func_noarguments);
 Start thread
 thr. Start ();
}
Function of No Arguments.

void Func_noarguments ()
{
 Debug.Log ("Run func_noarguments");
}

Two, the thread executes the parameter method

Construct syntax

Initializes a new instance of the Thread class.
//< param name= "start" > Parameter delegate object .</param> public
Thread (parameterizedthreadstart start)

Start

Type: System.Threading.ParameterizedThreadStart
A delegate that represents the method to invoke when this thread starts execution.
Note: The parameter can only have one and must be of type Object

Instance

void Start ()
{
 //Create a parametric thread object thread
 THR = new Thread (func_arguments);
 Start the thread and pass in the parameter
 thr. Start ("Lanou");
}
Function of Have Arguments.
void Func_arguments (Object data)
{
 Debug.Log ("Run func_arguments, data =" + data);
}

Third, the thread executes the parameterless method, restricting the maximum stack size that the thread will use

Construct syntax

Initializes a new instance of the Thread class.
//< param name= "start" > Non-Parametric delegate object .</param>
//< param name= "maxstacksize" > Maximum stack size used .</ Param> public
Thread (ThreadStart start,int maxstacksize)

Start

Type: System.Threading.ThreadStart
Represents the ThreadStart delegate for the method to invoke when this thread is started.

maxStackSize

Type: System.Int32
The maximum stack size (in bytes) to be used by the thread, or 0, using the default maximum stack size specified in the file header of the executable file.
Important: For partially trusted code, if maxStackSize is larger than the default stack size, it is ignored. Does not throw an exception.

void Start ()
{
 //Create parameterless thread object, limit 256KB stack size
 thread thr = new Thread (func_noarguments,262144);
 Start thread
 thr. Start ();
}
Function of No Arguments.
void Func_noarguments ()
{
 Debug.Log ("Run func_noarguments");
}

Four, the thread executes the parameter method, the limit thread to use the maximum stack size

Construct syntax

Initializes a new instance of the Thread class.
//< param name= "start" > Parameter Delegate object .</param>
//< param name= "maxstacksize" > Maximum stack size used .</ Param> public
Thread (Parameterizedthreadstart start,int maxstacksize)

Start

Type: System.Threading.ParameterizedThreadStart
A delegate that represents the method to invoke when this thread starts execution.
Note: The parameter can only have one and must be of type Object

maxStackSize

Type: System.Int32
The maximum stack size (in bytes) to be used by the thread, or 0, using the default maximum stack size specified in the file header of the executable file.
Important: For partially trusted code, if maxStackSize is larger than the default stack size, it is ignored. Does not throw an exception.

Instance

void Start ()
{
 //Create a parametric thread object that restricts the 256KB stack size
 thread thr = new Thread (func_arguments,262144);
 Start the thread and pass in the parameter
 thr. Start ("Lanou");
}
Function of Have Arguments.
void Func_arguments (Object data)
{
 Debug.Log ("Run func_arguments, data =" + data);
}

Start thread (used above)

No parameter start

void Start ()
{
 //Create a parameterless thread object thread
 THR = new Thread (func_noarguments);
 Start thread
 thr. Start ();
}
Function of No Arguments.
void Func_noarguments ()
{
 Debug.Log ("Run func_noarguments");
}

A parameter started

void Start ()
{
 //Create a parametric thread object thread
 THR = new Thread (func_arguments);
 Start the thread and pass in the parameter
 thr. Start ("Lanou");
}
Function of Have Arguments.
void Func_arguments (Object data)
{
 Debug.Log ("Run func_arguments, data =" + data);
}


Common methods

1.public static void sleep (int millisecondstimeout) suspends the current thread for the specified number of milliseconds.
(1) millisecondstimeout
Type: System.Int32
The number of milliseconds to suspend the thread. If the value of the millisecondstimeout parameter is zero, the thread gives the remainder of its time slice to any thread that is ready to run with equal priority. If there are no other threads that are ready to run and have the same priority, the execution of the current thread is not suspended.
(2) public void Resume ()
Continue the suspended thread. (OBSOLETE)
(3) public void Abort ()
Raises a ThreadAbortException on the thread that calls this method to begin the process of terminating the thread. Calling this method usually terminates the thread.
(4) public void Join ()
Blocks the calling thread until the thread terminates, while continuing to perform the standard COM and SendMessage transmissions.
(5) Public enum threadpriority
Specifies the scheduling priority for Thread.

Executing threads through a thread pool

2.threadpool.queueuserworkitem Method (WaitCallback)
public static bool QueueUserWorkItem (WaitCallback callBack)
CallBack
Type: System.Threading.WaitCallback
A waitcallback that represents the method to execute.
return value
Type: System.Boolean
True if this method queues successfully, and NotSupportedException is thrown if the work item cannot be queued.

Unity uses multithreading attention

Variables are shared (all can point to the same memory address)
Unityengine APIs cannot be run on a separate thread
The basic structure defined by Unityengine (int,float,struct defined data type) can be computed on a per-thread basis, such as Vector3 (Struct), but texture2d (class, the root parent class is Object) is not available.
Unityengine defined basic types of functions can be run on a separate thread
Unity Multithreaded Plugin

Loom Multi Threading Framework 1.7

Core approach

Unlike "Startmultithreadedworkloadexecution", you'll have to build your own ithreadworkerobject. Downside:it requires some extra work. Upside:you got more controll over what goes in and comes out//infact:you can create you own polymorphed Ithreadworker Object-array, each ellement being a completely different type. For example:the statemachines of enemies are Ithreadworkerobject ' s and the array contains completely different classes WI
 Th enemies/ai-behaviours. < param name= "workerobjects" >an array of Ithreadworkerobject objects to is handled by the threads. If you want multiple cores/threads is active, make sure this number of Ithreadworkerobject ' s proves matches/exeeds Your preferred number maxworkingthreads.  </param>//< param name= "OnComplete" >fired "all re-packaged" workload-objects are finished computing< /param>//< param name= "onpackageexecuted" >fires foreach finished re-packaged set of workload-object</para M>
 < param name= "MaxThreads" > lets you choose how many threads'll be run simultaneously by the ThreadPool. Default:-1 = = number of cores minus one, to make sure the mainthread has in least one core to run. (Quadcore = 1 Core mainthread, 3 cores used by the Threadpoolscheduler) </param>//< param name= "Scheduler" ; If Null, a new Threadpoolscheduler'll be instantiated.</param>//< param name= ' safemode ' >executes all th e computations within Try-catch events, logging it message + stacktrace</param>//< Returns>a Threadpoo Lscheduler that handles all the repackaged workload-objects</returns> public static Threadpoolscheduler Startmulti Threadedworkerobjects (ithreadworkerobject[] workerobjects, Threadpoolschedulerevent OnCompleteCallBack, Threadedworkcompleteevent onpackageexecuted = null, int maxthreads =-1, Threadpoolscheduler scheduler = NULL, BOOL Safemo De = True) {if (scheduler = null) Scheduler = CREATETHREADPOOlscheduler (); Scheduler.
 Startasyncthreads (Workerobjects, Oncompletecallback, onpackageexecuted, MaxThreads, SafeMode);
return scheduler;

 }


Conclusion

Unity can use multiple threads, but there are many limitations, so without using the Unityengine API, you can use multithreading to improve the usage of multi-core CPUs. It is usually possible to place algorithmic content that requires a lot of computation into multiple threads, including logical frameworks that can be executed in multiple threads. This article is strong in theory, later will be published in actual combat-type articles.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.