• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by Bunnybomb7670 · Feb 22, 2014 at 11:28 PM · objectlockthreadingthreadmulti

Weird Threading Issue

I have a thread manager class what handles threads and queues them so that I can have a thread-safe way of checking when a thread is finished. I have a GameObject calling the managers update loop every frame to check each threads state.

Manager class :

 using System;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ThreadTracker
 {
 
     public static List<ThreadObject> queue = new List<ThreadObject>();
     public static List<ThreadObject> threads = new List<ThreadObject>();
 
     public static int threadLimit = 8;
 
     static ThreadInstance instance;
 
     // Add a thread to the queue.
     public static void addThreadToQueue(ThreadObject obj)
     {
         if (obj == null)
         {
             throw new NullReferenceException();
         }
 
         checkThreadInstanceInitialized();
         //Logger.Log("Adding thread to queue");
         queue.Add(obj);
     }
 
     // Register a new thread into the list and start it.
     static void registerThreadHandler(ThreadObject obj)
     {
         //Logger.Log("Registering thread with ID value " + threads.Count + ".");
         obj.id = threads.Count;
         threads.Add(obj);
         threads[threads.Count - 1].startThread();
     }
 
     // Un-register and dispose of a finished thread.
     public static void unRegisterThreadHandler(int id)
     {
         //Logger.Log("Un-registering thread with ID value " + id + ".");
         threads.RemoveAt(id);
     }
 
     // Check whether the thread instance object is initialized.
     static void checkThreadInstanceInitialized()
     {
         if (instance == null)
         {
             instance = new GameObject().AddComponent<ThreadInstance>();
             instance.name = "Thread_Instance";
             instance.GetComponent<Transform>().hideFlags = HideFlags.HideInHierarchy;
         }
     }
 
     // Thread tracking loop. ( Called every frame )
     public static void threadTrackerLoop()
     {
         if (threads.Count > threadLimit)
         {
             throw new ThreadLimitExceededException();
         }
 
         for(int i = 0; i < threads.Count; i++)
         {
             if (threads[i].getThreadState() == true)
             {
                 threads[i].threadFinished();
             }
         }
 
         checkQueueForSlots();
     }
 
     // Check threads to see if there are any spare slots available.
     static void checkQueueForSlots()
     {
         int count = (threadLimit - threads.Count);
 
         for (int i = 0; i < count; i++)
         {
             if (queue.Count > 0)
             {
                 registerThreadHandler(queue[0]);
                 queue.RemoveAt(0);
             }
         }
 
     }
 
 }


Thread Object Class :

 using System;
 using System.Collections.Generic;
 using System.Threading;
 
 public class ThreadObject// : IThreadHandler
 {
 
     public object threadObject;
     private bool threadState = false;
     public int id = -1;
 
     public ThreadObject(int uniqueID)
     {
         id = uniqueID;
     }
 
     public ThreadObject()
     {
 
     }
 
     // Initialize thread lock object.
     public void initializeThreadData()
     {
         threadObject = new object();
     }
 
 
     // Start the thread.
     public void startThread()
     {
         initializeThreadData();
         Logger.Log("Thread with ID " + id + " has started.");
         Thread thread = new Thread(new ThreadStart(doThread));
         thread.Start();
     }
 
     // Called from the main thread to cleanup and finish.
     public void threadFinished()
     {
         Logger.Log("Thread with ID " + id + " has finished.");
         ThreadTracker.unRegisterThreadHandler(id);
     }
 
     // Thread base function
     void doThread()
     {
 
         Thread.Sleep(2350);
 
         finishThread();
     }
 
     // Called internally by the thread to finish itself.
     void finishThread()
     {
         setThreadState(true);
     }
 
     // Get the threads state.
     public bool getThreadState()
     {
         lock (threadObject)
         {
             return threadState;
         }
     }
 
     // Safely set the threads final state.
     public void setThreadState(bool state)
     {
         Monitor.Enter(threadObject);
         try
         {
             threadState = state;
         }
         finally
         {
             Monitor.Exit(threadObject);
         }
 
     }
 }


The problem is basically happening when the thread limit is reached, it literally starts another set of threads, instantly stops them again and so on until the thread list is empty, I am not sure what is causing this issue and it would be very helpful for some hints to why it happens.

Comment

People who like this

0 Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunnybomb7670 · Feb 23, 2014 at 12:15 AM 0
Share

Is there something I am doing what is incorrect?

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multithreading, Waiting for threads to complete. 0 Answers

Making calls to Spotify REST API blocks main thread 2 Answers

What does new Thread do, and how many threads are too many? 1 Answer

LobbyHook doesn't give clients variables 0 Answers

How to spawn lots of objects without freezing the game 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges