The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

328 lines
10.0KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: MultithreadingDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Demonstrates multi-threading.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics
  26. exporters: xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: MultithreadingDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. //==============================================================================
  36. class BouncingBall : private ComponentListener
  37. {
  38. public:
  39. BouncingBall (Component& comp)
  40. : containerComponent (comp)
  41. {
  42. containerComponent.addComponentListener (this);
  43. auto speed = 5.0f; // give each ball a fixed speed so we can
  44. // see the effects of thread priority on how fast
  45. // they actually go.
  46. auto angle = Random::getSystemRandom().nextFloat() * MathConstants<float>::twoPi;
  47. dx = std::sin (angle) * speed;
  48. dy = std::cos (angle) * speed;
  49. colour = Colour ((juce::uint32) Random::getSystemRandom().nextInt())
  50. .withAlpha (0.5f)
  51. .withBrightness (0.7f);
  52. componentMovedOrResized (containerComponent, true, true);
  53. x = Random::getSystemRandom().nextFloat() * parentWidth;
  54. y = Random::getSystemRandom().nextFloat() * parentHeight;
  55. }
  56. ~BouncingBall() override
  57. {
  58. containerComponent.removeComponentListener (this);
  59. }
  60. // This will be called from the message thread
  61. void draw (Graphics& g)
  62. {
  63. const ScopedLock lock (drawing);
  64. g.setColour (colour);
  65. g.fillEllipse (x, y, size, size);
  66. g.setColour (Colours::black);
  67. g.setFont (10.0f);
  68. g.drawText (String::toHexString ((int64) threadId), Rectangle<float> (x, y, size, size), Justification::centred, false);
  69. }
  70. void moveBall()
  71. {
  72. const ScopedLock lock (drawing);
  73. threadId = Thread::getCurrentThreadId(); // this is so the component can print the thread ID inside the ball
  74. x += dx;
  75. y += dy;
  76. if (x < 0)
  77. dx = std::abs (dx);
  78. if (x > parentWidth)
  79. dx = -std::abs (dx);
  80. if (y < 0)
  81. dy = std::abs (dy);
  82. if (y > parentHeight)
  83. dy = -std::abs (dy);
  84. }
  85. private:
  86. void componentMovedOrResized (Component& comp, bool, bool) override
  87. {
  88. const ScopedLock lock (drawing);
  89. parentWidth = (float) comp.getWidth() - size;
  90. parentHeight = (float) comp.getHeight() - size;
  91. }
  92. float x = 0.0f, y = 0.0f,
  93. size = Random::getSystemRandom().nextFloat() * 30.0f + 30.0f,
  94. dx = 0.0f, dy = 0.0f,
  95. parentWidth = 50.0f, parentHeight = 50.0f;
  96. Colour colour;
  97. Thread::ThreadID threadId = {};
  98. CriticalSection drawing;
  99. Component& containerComponent;
  100. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BouncingBall)
  101. };
  102. //==============================================================================
  103. class DemoThread : public BouncingBall,
  104. public Thread
  105. {
  106. public:
  107. DemoThread (Component& containerComp)
  108. : BouncingBall (containerComp),
  109. Thread ("JUCE Demo Thread")
  110. {
  111. startThread();
  112. }
  113. ~DemoThread() override
  114. {
  115. // allow the thread 2 seconds to stop cleanly - should be plenty of time.
  116. stopThread (2000);
  117. }
  118. void run() override
  119. {
  120. // this is the code that runs this thread - we'll loop continuously,
  121. // updating the coordinates of our blob.
  122. // threadShouldExit() returns true when the stopThread() method has been
  123. // called, so we should check it often, and exit as soon as it gets flagged.
  124. while (! threadShouldExit())
  125. {
  126. // sleep a bit so the threads don't all grind the CPU to a halt..
  127. wait (interval);
  128. // because this is a background thread, we mustn't do any UI work without
  129. // first grabbing a MessageManagerLock..
  130. const MessageManagerLock mml (Thread::getCurrentThread());
  131. if (! mml.lockWasGained()) // if something is trying to kill this job, the lock
  132. return; // will fail, in which case we'd better return..
  133. // now we've got the UI thread locked, we can mess about with the components
  134. moveBall();
  135. }
  136. }
  137. private:
  138. int interval = Random::getSystemRandom().nextInt (50) + 6;
  139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoThread)
  140. };
  141. //==============================================================================
  142. class DemoThreadPoolJob : public BouncingBall,
  143. public ThreadPoolJob
  144. {
  145. public:
  146. DemoThreadPoolJob (Component& containerComp)
  147. : BouncingBall (containerComp),
  148. ThreadPoolJob ("Demo Threadpool Job")
  149. {}
  150. JobStatus runJob() override
  151. {
  152. // this is the code that runs this job. It'll be repeatedly called until we return
  153. // jobHasFinished instead of jobNeedsRunningAgain.
  154. Thread::sleep (30);
  155. // because this is a background thread, we mustn't do any UI work without
  156. // first grabbing a MessageManagerLock..
  157. const MessageManagerLock mml (this);
  158. // before moving the ball, we need to check whether the lock was actually gained, because
  159. // if something is trying to stop this job, it will have failed..
  160. if (mml.lockWasGained())
  161. moveBall();
  162. return jobNeedsRunningAgain;
  163. }
  164. void removedFromQueue()
  165. {
  166. // This is called to tell us that our job has been removed from the pool.
  167. // In this case there's no need to do anything here.
  168. }
  169. private:
  170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoThreadPoolJob)
  171. };
  172. //==============================================================================
  173. class MultithreadingDemo : public Component,
  174. private Timer
  175. {
  176. public:
  177. //==============================================================================
  178. MultithreadingDemo()
  179. {
  180. setOpaque (true);
  181. addAndMakeVisible (controlButton);
  182. controlButton.changeWidthToFitText (24);
  183. controlButton.setTopLeftPosition (20, 20);
  184. controlButton.setTriggeredOnMouseDown (true);
  185. controlButton.setAlwaysOnTop (true);
  186. controlButton.onClick = [this] { showMenu(); };
  187. setSize (500, 500);
  188. resetAllBalls();
  189. startTimerHz (60);
  190. }
  191. ~MultithreadingDemo() override
  192. {
  193. pool.removeAllJobs (true, 2000);
  194. }
  195. void resetAllBalls()
  196. {
  197. pool.removeAllJobs (true, 4000);
  198. balls.clear();
  199. for (int i = 0; i < 5; ++i)
  200. addABall();
  201. }
  202. void paint (Graphics& g) override
  203. {
  204. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  205. for (auto* ball : balls)
  206. ball->draw (g);
  207. }
  208. private:
  209. //==============================================================================
  210. void setUsingPool (bool usePool)
  211. {
  212. isUsingPool = usePool;
  213. resetAllBalls();
  214. }
  215. void addABall()
  216. {
  217. if (isUsingPool)
  218. {
  219. auto newBall = std::make_unique<DemoThreadPoolJob> (*this);
  220. pool.addJob (newBall.get(), false);
  221. balls.add (newBall.release());
  222. }
  223. else
  224. {
  225. balls.add (new DemoThread (*this));
  226. }
  227. }
  228. void timerCallback() override
  229. {
  230. repaint();
  231. }
  232. void showMenu()
  233. {
  234. PopupMenu m;
  235. m.addItem (1, "Use one thread per ball", true, ! isUsingPool);
  236. m.addItem (2, "Use a thread pool", true, isUsingPool);
  237. m.showMenuAsync (PopupMenu::Options().withTargetComponent (controlButton),
  238. ModalCallbackFunction::forComponent (menuItemChosenCallback, this));
  239. }
  240. static void menuItemChosenCallback (int result, MultithreadingDemo* demoComponent)
  241. {
  242. if (result != 0 && demoComponent != nullptr)
  243. demoComponent->setUsingPool (result == 2);
  244. }
  245. //==============================================================================
  246. ThreadPool pool { 3 };
  247. TextButton controlButton { "Thread type" };
  248. bool isUsingPool = false;
  249. OwnedArray<BouncingBall> balls;
  250. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultithreadingDemo)
  251. };