2

Executing multithreaded methods make garbage. Why is that and can we prevent it?

ThreadPool.QueueUserWorkItem(callBack, state);

enter image description here

EDIT: By garbage I mean objects that are created and then went out of scope. The garbage collection is very slow because of it's old version of mono. So every kb you save from the GC is a win. If you are not familiar with the unity engine, In the screenshot please see The GC column on the highlighted row. It says 0.6kb. Therefore it create 600 bytes of garbage. The callback code is not creating any garbage so this is rooted from ThreadPool.QueueUserWorkItem

EDIT 2: To elaborate further here is a more concrete example:

public class TestThread : MonoBehaviour
{
    public void Update()
    {
        if (Time.frameCount%10 == 0)
            ThreadPool.QueueUserWorkItem(DummyMethod);
    }

    public void DummyMethod(object meaningless)
    {
    }
}

Here is the result. Please look at the highlighted row. The GC column says 285Bytes. Since DummyMethod is not doing anything, the garbage is related to ThreadPool.

enter image description here

Edit 3: To relax the situation and find an alternative, it would be acceptable to have a worker thread that executes jobs from a queue.

It would be OK But it MUST run on CPU other than the one unity uses if there are multiple CPUs available. Unity does nearly anything in a single thread so a background worker on the same CPU would be a disaster. Also it is a cross platform project so windows-only solutions won't work. So basically I need a worker thread solution and to know if it possible to realize if a thread's CPU is the same as another thread's.

16
  • 5
    "Make garbage"? What does that mean? Jan 15, 2016 at 14:25
  • 5
    Doing pretty much anything will create garbage that will later need cleanup. In general though, multi-threading means overhead. It's the nature of the beast. Jan 15, 2016 at 14:28
  • 3
    17 kb gc allocated. is that a problem? Jan 15, 2016 at 14:33
  • 3
    Without any code showing what you are actually doing in those threads, I'm not sure how you think the question is going to be answerable. Jan 15, 2016 at 14:35
  • 2
    If 17kb really is an issue, you could try not to use the ThreadPool, but directly create threads yourself. Possibly implement your own garbage-free(TM) thread pool ?
    – MarkO
    Jan 15, 2016 at 14:38

1 Answer 1

5

When you ThreadPool.QueueUserWorkItem(DummyMethod); it actually is implicitly turning your code in to ThreadPool.QueueUserWorkItem(new WaitCallback(DummyMethod));, that callback may be the item that is getting put on to the GC. Try the following code to explicitly create the delegate and keep a reference to it and see if it reduces the amount of GCable data.

public class TestThread : MonoBehaviour
{
    private readonly WaitCallback _callback;

    public TestThread()
    {
        _callback = new WaitCallback(DummyMethod);
    }

    public void Update()
    {
        if (Time.frameCount%10 == 0)
            ThreadPool.QueueUserWorkItem(_callback);
    }

    public void DummyMethod(object meaningless)
    {
    }
}

UPDATE: Here is a extremely basic implementation of a single threaded background worker, to give you a starting point. The below code is untested and may perform horribly, but it does give you an idea as a starting point.

public class BasicBackgroundWorker
{
    private readonly Thread _backgroundWorkThread;
    private readonly Queue<Action> _queue = new Queue<Action>();
    private readonly ManualResetEvent _workAvailable = new ManualResetEvent(false);

    public BasicBackgroundWorker()
    {
        _backgroundWorkThread = new Thread(BackgroundThread)
        {
            IsBackground = true,
            Priority = ThreadPriority.BelowNormal,
            Name = "BasicBackgroundWorker Thread"
        };
        _backgroundWorkThread.Start();
    }

    public void EnqueueWork(Action work)
    {
        lock (_queue)
        {
            _queue.Enqueue(work);
            _workAvailable.Set();
        }
    }

    private void BackgroundThread()
    {
        while (true)
        {
            _workAvailable.WaitOne();
            Action workItem;
            lock (_queue)
            {
                workItem = _queue.Dequeue();
                if (_queue.Count == 0)
                {
                    _workAvailable.Reset();
                }
            }
            try
            {
                workItem();
            }
            catch (Exception ex)
            {
                //Log exception that happened in backgroundWork
            }
        }
    }
}
9
  • That helped 16 bytes. Thanks. Jan 15, 2016 at 16:41
  • 1
    I don't think you can get any better while still using QueueUserWorkItem, any other improvements would require writing a custom Thread Pool you write yourself. Jan 15, 2016 at 16:50
  • 1
    Does Unity let you do new Thread(WorkerMethod) { IsBackground = true };? If so you could set up a dedicated background worker that pulled from a BlockingCollection<T> of work. Jan 15, 2016 at 17:02
  • 1
    You should not care about what CPU it is on. Just set the Thread Priority to low. The UI thread runs on all CPUs it jumps from CPU to CPU as context switches happen, it does not have a CPU affinity. Forcing it to be "not on the same CPU" would also cause your code to not run at all on single core machines. Jan 15, 2016 at 17:22
  • 2
    I have updated my answer with a very basic background worker for you to use as a starting point. Jan 15, 2016 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.