Forum Scripting Unity Error due to multithreading?

Post your problems and discussions relating to scripting in Unity here.

Unity Error due to multithreading?

Postby Izzimach » January 26th, 2011, 6:05 am

I was testing out some unity client code which is basically a hacked up version of the PlayerIO Unity example and happened upon this error.

"InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List`1+Enumerator[PlayerIOClient.Message].VerifyState ()
System.Collections.Generic.List`1+Enumerator[PlayerIOClient.Message].MoveNext ()
GameManager.FixedUpdate () (at Assets/Scripts/GameManager.cs:104)
"

A not so helpful screenshot of the Unity console is here

Normally when messages trickle in they are dumped into the message list (named msglist) which is then processed during FixedUpdate(). Here it appears that the message list is being modified while I'm processing the messages. Is this probably due to a PlayerIO thread calling handlemessage() while I'm processing messages? If so, I should either lock the message list while processing it or maintain two message lists and flip between the two (using locks) on each call to FixedUpdate().

Thanks for any help or insight guys!
User avatar
Izzimach
 
Posts: 4
Joined: January 17th, 2011, 7:17 pm
Location: Rocky Mountain High

Re: Unity Error due to multithreading?

Postby Oliver » January 27th, 2011, 1:57 pm

Yep, callbacks are mutithreaded, so they can occur any time.

The best solution in your cause is to use a lock when accessing the list or, as you mention, some clever locking and two (or more lists).

I've done something similar in another project where the incoming messages are added like this:

Code: Select all
lock(this){
   list.Add(m)
}


And when i need to process the list i'll do something like this:

Code: Select all
Message[] processList;
lock(this){
   processList = list.ToArray(); // copy out all the received messages
   list.Clear(); // clear the list
}
//.. process all the messages in processList


That way, you aren't keeping a lock while you're processing the messages at the expense of a little bit of data copying.

Best,
Oliver
User avatar
Oliver
.IO
 
Posts: 1159
Joined: January 12th, 2010, 8:29 am


Return to Scripting



cron