File: MultithreadingDemo.h

package info (click to toggle)
juce 8.0.6%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 78,204 kB
  • sloc: cpp: 521,891; ansic: 159,819; java: 2,996; javascript: 847; xml: 273; python: 224; sh: 162; makefile: 84
file content (337 lines) | stat: -rw-r--r-- 10,762 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
  ==============================================================================

   This file is part of the JUCE framework examples.
   Copyright (c) Raw Material Software Limited

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   to use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
   REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
   AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
   INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
   LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
   OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
   PERFORMANCE OF THIS SOFTWARE.

  ==============================================================================
*/

/*******************************************************************************
 The block below describes the properties of this PIP. A PIP is a short snippet
 of code that can be read by the Projucer and used to generate a JUCE project.

 BEGIN_JUCE_PIP_METADATA

 name:             MultithreadingDemo
 version:          1.0.0
 vendor:           JUCE
 website:          http://juce.com
 description:      Demonstrates multi-threading.

 dependencies:     juce_core, juce_data_structures, juce_events, juce_graphics,
                   juce_gui_basics
 exporters:        xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone

 moduleFlags:      JUCE_STRICT_REFCOUNTEDPOINTER=1

 type:             Component
 mainClass:        MultithreadingDemo

 useLocalCopy:     1

 END_JUCE_PIP_METADATA

*******************************************************************************/

#pragma once

#include "../Assets/DemoUtilities.h"

//==============================================================================
class BouncingBall : private ComponentListener
{
public:
    BouncingBall (Component& comp)
        : containerComponent (comp)
    {
        containerComponent.addComponentListener (this);

        auto speed = 5.0f; // give each ball a fixed speed so we can
                           // see the effects of thread priority on how fast
                           // they actually go.

        auto angle = Random::getSystemRandom().nextFloat() * MathConstants<float>::twoPi;

        dx = std::sin (angle) * speed;
        dy = std::cos (angle) * speed;

        colour = Colour ((juce::uint32) Random::getSystemRandom().nextInt())
                    .withAlpha (0.5f)
                    .withBrightness (0.7f);

        updateParentSize (comp);

        x = Random::getSystemRandom().nextFloat() * parentWidth;
        y = Random::getSystemRandom().nextFloat() * parentHeight;
    }

    ~BouncingBall() override
    {
        containerComponent.removeComponentListener (this);
    }

    // This will be called from the message thread
    void draw (Graphics& g)
    {
        const ScopedLock lock (drawing);

        g.setColour (colour);
        g.fillEllipse (x, y, size, size);

        g.setColour (Colours::black);
        g.setFont (10.0f);
        g.drawText (String::toHexString ((int64) threadId), Rectangle<float> (x, y, size, size), Justification::centred, false);
    }

    void moveBall()
    {
        const ScopedLock lock (drawing);

        threadId = Thread::getCurrentThreadId(); // this is so the component can print the thread ID inside the ball

        x += dx;
        y += dy;

        if (x < 0)
            dx = std::abs (dx);

        if (x > parentWidth)
            dx = -std::abs (dx);

        if (y < 0)
            dy = std::abs (dy);

        if (y > parentHeight)
            dy = -std::abs (dy);
    }

private:
    void updateParentSize (Component& comp)
    {
        const ScopedLock lock (drawing);

        parentWidth  = (float) comp.getWidth()  - size;
        parentHeight = (float) comp.getHeight() - size;
    }

    void componentMovedOrResized (Component& comp, bool, bool) override
    {
        updateParentSize (comp);
    }

    float x = 0.0f, y = 0.0f,
          size = Random::getSystemRandom().nextFloat() * 30.0f + 30.0f,
          dx = 0.0f, dy = 0.0f,
          parentWidth = 50.0f, parentHeight = 50.0f;

    Colour colour;
    Thread::ThreadID threadId = {};
    CriticalSection drawing;

    Component& containerComponent;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BouncingBall)
};

//==============================================================================
class DemoThread final : public BouncingBall,
                         public Thread
{
public:
    DemoThread (Component& containerComp)
        : BouncingBall (containerComp),
          Thread ("JUCE Demo Thread")
    {
        startThread();
    }

    ~DemoThread() override
    {
        // allow the thread 2 seconds to stop cleanly - should be plenty of time.
        stopThread (2000);
    }

    void run() override
    {
        // this is the code that runs this thread - we'll loop continuously,
        // updating the coordinates of our blob.

        // threadShouldExit() returns true when the stopThread() method has been
        // called, so we should check it often, and exit as soon as it gets flagged.
        while (! threadShouldExit())
        {
            // sleep a bit so the threads don't all grind the CPU to a halt..
            wait (interval);

            // because this is a background thread, we mustn't do any UI work without
            // first grabbing a MessageManagerLock..
            const MessageManagerLock mml (Thread::getCurrentThread());

            if (! mml.lockWasGained())  // if something is trying to kill this job, the lock
                return;                 // will fail, in which case we'd better return..

            // now we've got the UI thread locked, we can mess about with the components
            moveBall();
        }
    }

private:
    int interval = Random::getSystemRandom().nextInt (50) + 6;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoThread)
};


//==============================================================================
class DemoThreadPoolJob final : public BouncingBall,
                                public ThreadPoolJob
{
public:
    DemoThreadPoolJob (Component& containerComp)
        : BouncingBall (containerComp),
          ThreadPoolJob ("Demo Threadpool Job")
    {}

    JobStatus runJob() override
    {
        // this is the code that runs this job. It'll be repeatedly called until we return
        // jobHasFinished instead of jobNeedsRunningAgain.
        Thread::sleep (30);

        // because this is a background thread, we mustn't do any UI work without
        // first grabbing a MessageManagerLock..
        const MessageManagerLock mml (this);

        // before moving the ball, we need to check whether the lock was actually gained, because
        // if something is trying to stop this job, it will have failed..
        if (mml.lockWasGained())
            moveBall();

        return jobNeedsRunningAgain;
    }

    void removedFromQueue()
    {
        // This is called to tell us that our job has been removed from the pool.
        // In this case there's no need to do anything here.
    }

private:
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoThreadPoolJob)
};

//==============================================================================
class MultithreadingDemo final : public Component,
                                 private Timer
{
public:
    //==============================================================================
    MultithreadingDemo()
    {
        setOpaque (true);

        addAndMakeVisible (controlButton);
        controlButton.changeWidthToFitText (24);
        controlButton.setTopLeftPosition (20, 20);
        controlButton.setTriggeredOnMouseDown (true);
        controlButton.setAlwaysOnTop (true);
        controlButton.onClick = [this] { showMenu(); };

        setSize (500, 500);

        resetAllBalls();

        startTimerHz (60);
    }

    ~MultithreadingDemo() override
    {
        pool.removeAllJobs (true, 2000);
    }

    void resetAllBalls()
    {
        pool.removeAllJobs (true, 4000);
        balls.clear();

        for (int i = 0; i < 5; ++i)
            addABall();
    }

    void paint (Graphics& g) override
    {
        g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));

        for (auto* ball : balls)
            ball->draw (g);
    }

private:
    //==============================================================================
    void setUsingPool (bool usePool)
    {
        isUsingPool = usePool;
        resetAllBalls();
    }

    void addABall()
    {
        if (isUsingPool)
        {
            auto newBall = std::make_unique<DemoThreadPoolJob> (*this);
            pool.addJob (newBall.get(), false);
            balls.add (newBall.release());

        }
        else
        {
            balls.add (new DemoThread (*this));
        }
    }

    void timerCallback() override
    {
        repaint();
    }

    void showMenu()
    {
        PopupMenu m;
        m.addItem (1, "Use one thread per ball", true, ! isUsingPool);
        m.addItem (2, "Use a thread pool",       true,   isUsingPool);

        m.showMenuAsync (PopupMenu::Options().withTargetComponent (controlButton),
                         ModalCallbackFunction::forComponent (menuItemChosenCallback, this));
    }

    static void menuItemChosenCallback (int result, MultithreadingDemo* demoComponent)
    {
        if (result != 0 && demoComponent != nullptr)
            demoComponent->setUsingPool (result == 2);
    }

    //==============================================================================
    ThreadPool pool           { ThreadPoolOptions{}.withThreadName ("Demo thread pool")
                                                   .withNumberOfThreads (3) };
    TextButton controlButton  { "Thread type" };
    bool isUsingPool = false;

    OwnedArray<BouncingBall> balls;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultithreadingDemo)
};