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.

330 lines
10KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - 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, vs2019, 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. // give the threads a random priority, so some will move more
  112. // smoothly than others..
  113. startThread (Random::getSystemRandom().nextInt (3) + 3);
  114. }
  115. ~DemoThread() override
  116. {
  117. // allow the thread 2 seconds to stop cleanly - should be plenty of time.
  118. stopThread (2000);
  119. }
  120. void run() override
  121. {
  122. // this is the code that runs this thread - we'll loop continuously,
  123. // updating the coordinates of our blob.
  124. // threadShouldExit() returns true when the stopThread() method has been
  125. // called, so we should check it often, and exit as soon as it gets flagged.
  126. while (! threadShouldExit())
  127. {
  128. // sleep a bit so the threads don't all grind the CPU to a halt..
  129. wait (interval);
  130. // because this is a background thread, we mustn't do any UI work without
  131. // first grabbing a MessageManagerLock..
  132. const MessageManagerLock mml (Thread::getCurrentThread());
  133. if (! mml.lockWasGained()) // if something is trying to kill this job, the lock
  134. return; // will fail, in which case we'd better return..
  135. // now we've got the UI thread locked, we can mess about with the components
  136. moveBall();
  137. }
  138. }
  139. private:
  140. int interval = Random::getSystemRandom().nextInt (50) + 6;
  141. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoThread)
  142. };
  143. //==============================================================================
  144. class DemoThreadPoolJob : public BouncingBall,
  145. public ThreadPoolJob
  146. {
  147. public:
  148. DemoThreadPoolJob (Component& containerComp)
  149. : BouncingBall (containerComp),
  150. ThreadPoolJob ("Demo Threadpool Job")
  151. {}
  152. JobStatus runJob() override
  153. {
  154. // this is the code that runs this job. It'll be repeatedly called until we return
  155. // jobHasFinished instead of jobNeedsRunningAgain.
  156. Thread::sleep (30);
  157. // because this is a background thread, we mustn't do any UI work without
  158. // first grabbing a MessageManagerLock..
  159. const MessageManagerLock mml (this);
  160. // before moving the ball, we need to check whether the lock was actually gained, because
  161. // if something is trying to stop this job, it will have failed..
  162. if (mml.lockWasGained())
  163. moveBall();
  164. return jobNeedsRunningAgain;
  165. }
  166. void removedFromQueue()
  167. {
  168. // This is called to tell us that our job has been removed from the pool.
  169. // In this case there's no need to do anything here.
  170. }
  171. private:
  172. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoThreadPoolJob)
  173. };
  174. //==============================================================================
  175. class MultithreadingDemo : public Component,
  176. private Timer
  177. {
  178. public:
  179. //==============================================================================
  180. MultithreadingDemo()
  181. {
  182. setOpaque (true);
  183. addAndMakeVisible (controlButton);
  184. controlButton.changeWidthToFitText (24);
  185. controlButton.setTopLeftPosition (20, 20);
  186. controlButton.setTriggeredOnMouseDown (true);
  187. controlButton.setAlwaysOnTop (true);
  188. controlButton.onClick = [this] { showMenu(); };
  189. setSize (500, 500);
  190. resetAllBalls();
  191. startTimerHz (60);
  192. }
  193. ~MultithreadingDemo() override
  194. {
  195. pool.removeAllJobs (true, 2000);
  196. }
  197. void resetAllBalls()
  198. {
  199. pool.removeAllJobs (true, 4000);
  200. balls.clear();
  201. for (int i = 0; i < 5; ++i)
  202. addABall();
  203. }
  204. void paint (Graphics& g) override
  205. {
  206. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  207. for (auto* ball : balls)
  208. ball->draw (g);
  209. }
  210. private:
  211. //==============================================================================
  212. void setUsingPool (bool usePool)
  213. {
  214. isUsingPool = usePool;
  215. resetAllBalls();
  216. }
  217. void addABall()
  218. {
  219. if (isUsingPool)
  220. {
  221. auto newBall = std::make_unique<DemoThreadPoolJob> (*this);
  222. pool.addJob (newBall.get(), false);
  223. balls.add (newBall.release());
  224. }
  225. else
  226. {
  227. balls.add (new DemoThread (*this));
  228. }
  229. }
  230. void timerCallback() override
  231. {
  232. repaint();
  233. }
  234. void showMenu()
  235. {
  236. PopupMenu m;
  237. m.addItem (1, "Use one thread per ball", true, ! isUsingPool);
  238. m.addItem (2, "Use a thread pool", true, isUsingPool);
  239. m.showMenuAsync (PopupMenu::Options().withTargetComponent (controlButton),
  240. ModalCallbackFunction::forComponent (menuItemChosenCallback, this));
  241. }
  242. static void menuItemChosenCallback (int result, MultithreadingDemo* demoComponent)
  243. {
  244. if (result != 0 && demoComponent != nullptr)
  245. demoComponent->setUsingPool (result == 2);
  246. }
  247. //==============================================================================
  248. ThreadPool pool { 3 };
  249. TextButton controlButton { "Thread type" };
  250. bool isUsingPool = false;
  251. OwnedArray<BouncingBall> balls;
  252. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultithreadingDemo)
  253. };