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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
|
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
Thread::Thread (const String& name, size_t stackSize) : threadName (name),
threadStackSize (stackSize)
{
}
Thread::~Thread()
{
if (deleteOnThreadEnd)
return;
/* If your thread class's destructor has been called without first stopping the thread, that
means that this partially destructed object is still performing some work - and that's
probably a Bad Thing!
To avoid this type of nastiness, always make sure you call stopThread() before or during
your subclass's destructor.
*/
jassert (! isThreadRunning());
stopThread (-1);
}
//==============================================================================
// Use a ref-counted object to hold this shared data, so that it can outlive its static
// shared pointer when threads are still running during static shutdown.
struct CurrentThreadHolder final : public ReferenceCountedObject
{
CurrentThreadHolder() noexcept {}
using Ptr = ReferenceCountedObjectPtr<CurrentThreadHolder>;
ThreadLocalValue<Thread*> value;
JUCE_DECLARE_NON_COPYABLE (CurrentThreadHolder)
};
static char currentThreadHolderLock [sizeof (SpinLock)]; // (statically initialised to zeros).
static SpinLock* castToSpinLockWithoutAliasingWarning (void* s)
{
return static_cast<SpinLock*> (s);
}
static CurrentThreadHolder::Ptr getCurrentThreadHolder()
{
static CurrentThreadHolder::Ptr currentThreadHolder;
SpinLock::ScopedLockType lock (*castToSpinLockWithoutAliasingWarning (currentThreadHolderLock));
if (currentThreadHolder == nullptr)
currentThreadHolder = new CurrentThreadHolder();
return currentThreadHolder;
}
void Thread::threadEntryPoint()
{
const CurrentThreadHolder::Ptr currentThreadHolder (getCurrentThreadHolder());
currentThreadHolder->value = this;
if (threadName.isNotEmpty())
setCurrentThreadName (threadName);
// This 'startSuspensionEvent' protects 'threadId' which is initialised after the platform's native 'CreateThread' method.
// This ensures it has been initialised correctly before it reaches this point.
if (startSuspensionEvent.wait (10000))
{
jassert (getCurrentThreadId() == threadId);
if (affinityMask != 0)
setCurrentThreadAffinityMask (affinityMask);
try
{
run();
}
catch (...)
{
jassertfalse; // Your run() method mustn't throw any exceptions!
}
}
currentThreadHolder->value.releaseCurrentThreadStorage();
// Once closeThreadHandle is called this class may be deleted by a different
// thread, so we need to store deleteOnThreadEnd in a local variable.
auto shouldDeleteThis = deleteOnThreadEnd;
closeThreadHandle();
if (shouldDeleteThis)
delete this;
}
// used to wrap the incoming call from the platform-specific code
void JUCE_API juce_threadEntryPoint (void* userData)
{
static_cast<Thread*> (userData)->threadEntryPoint();
}
//==============================================================================
bool Thread::startThreadInternal (Priority threadPriority)
{
shouldExit = false;
// 'priority' is essentially useless on Linux as only realtime
// has any options but we need to set this here to satisfy
// later queries, otherwise we get inconsistent results across
// platforms.
#if JUCE_ANDROID || JUCE_LINUX || JUCE_BSD
priority = threadPriority;
#endif
if (createNativeThread (threadPriority))
{
startSuspensionEvent.signal();
return true;
}
return false;
}
bool Thread::startThread()
{
return startThread (Priority::normal);
}
bool Thread::startThread (Priority threadPriority)
{
const ScopedLock sl (startStopLock);
if (threadHandle == nullptr)
{
realtimeOptions.reset();
return startThreadInternal (threadPriority);
}
return false;
}
bool Thread::startRealtimeThread (const RealtimeOptions& options)
{
const ScopedLock sl (startStopLock);
if (threadHandle == nullptr)
{
realtimeOptions = std::make_optional (options);
if (startThreadInternal (Priority::normal))
return true;
realtimeOptions.reset();
}
return false;
}
bool Thread::isThreadRunning() const
{
return threadHandle != nullptr;
}
Thread* JUCE_CALLTYPE Thread::getCurrentThread()
{
return getCurrentThreadHolder()->value.get();
}
Thread::ThreadID Thread::getThreadId() const noexcept
{
return threadId;
}
//==============================================================================
void Thread::signalThreadShouldExit()
{
shouldExit = true;
listeners.call ([] (Listener& l) { l.exitSignalSent(); });
}
bool Thread::threadShouldExit() const
{
return shouldExit;
}
bool Thread::currentThreadShouldExit()
{
if (auto* currentThread = getCurrentThread())
return currentThread->threadShouldExit();
return false;
}
bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
{
// Doh! So how exactly do you expect this thread to wait for itself to stop??
jassert (getThreadId() != getCurrentThreadId() || getCurrentThreadId() == ThreadID());
auto timeoutEnd = Time::getMillisecondCounter() + (uint32) timeOutMilliseconds;
while (isThreadRunning())
{
if (timeOutMilliseconds >= 0 && Time::getMillisecondCounter() > timeoutEnd)
return false;
sleep (2);
}
return true;
}
bool Thread::stopThread (const int timeOutMilliseconds)
{
// agh! You can't stop the thread that's calling this method! How on earth
// would that work??
jassert (getCurrentThreadId() != getThreadId());
const ScopedLock sl (startStopLock);
if (isThreadRunning())
{
signalThreadShouldExit();
notify();
if (timeOutMilliseconds != 0)
waitForThreadToExit (timeOutMilliseconds);
if (isThreadRunning())
{
// very bad karma if this point is reached, as there are bound to be
// locks and events left in silly states when a thread is killed by force..
jassertfalse;
Logger::writeToLog ("!! killing thread by force !!");
killThread();
threadHandle = nullptr;
threadId = {};
return false;
}
}
return true;
}
void Thread::addListener (Listener* listener)
{
listeners.add (listener);
}
void Thread::removeListener (Listener* listener)
{
listeners.remove (listener);
}
bool Thread::isRealtime() const
{
return realtimeOptions.has_value();
}
void Thread::setAffinityMask (const uint32 newAffinityMask)
{
affinityMask = newAffinityMask;
}
//==============================================================================
bool Thread::wait (double timeOutMilliseconds) const
{
return defaultEvent.wait (timeOutMilliseconds);
}
void Thread::notify() const
{
defaultEvent.signal();
}
//==============================================================================
struct LambdaThread final : public Thread
{
LambdaThread (std::function<void()>&& f) : Thread (SystemStats::getJUCEVersion() + ": anonymous"), fn (std::move (f)) {}
void run() override
{
fn();
fn = nullptr; // free any objects that the lambda might contain while the thread is still active
}
std::function<void()> fn;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LambdaThread)
};
bool Thread::launch (std::function<void()> functionToRun)
{
return launch (Priority::normal, std::move (functionToRun));
}
bool Thread::launch (Priority priority, std::function<void()> functionToRun)
{
auto anon = std::make_unique<LambdaThread> (std::move (functionToRun));
anon->deleteOnThreadEnd = true;
if (anon->startThread (priority))
{
anon.release();
return true;
}
return false;
}
//==============================================================================
void SpinLock::enter() const noexcept
{
if (! tryEnter())
{
for (int i = 20; --i >= 0;)
if (tryEnter())
return;
while (! tryEnter())
Thread::yield();
}
}
//==============================================================================
bool JUCE_CALLTYPE Process::isRunningUnderDebugger() noexcept
{
return juce_isRunningUnderDebugger();
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
class AtomicTests final : public UnitTest
{
public:
AtomicTests()
: UnitTest ("Atomics", UnitTestCategories::threads)
{}
void runTest() override
{
beginTest ("Misc");
char a1[7];
expect (numElementsInArray (a1) == 7);
int a2[3];
expect (numElementsInArray (a2) == 3);
expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
expect (ByteOrder::swap ((uint64) 0x1122334455667788ULL) == (uint64) 0x8877665544332211LL);
beginTest ("Atomic int");
AtomicTester <int>::testInteger (*this);
beginTest ("Atomic unsigned int");
AtomicTester <unsigned int>::testInteger (*this);
beginTest ("Atomic int32");
AtomicTester <int32>::testInteger (*this);
beginTest ("Atomic uint32");
AtomicTester <uint32>::testInteger (*this);
beginTest ("Atomic long");
AtomicTester <long>::testInteger (*this);
beginTest ("Atomic int*");
AtomicTester <int*>::testInteger (*this);
beginTest ("Atomic float");
AtomicTester <float>::testFloat (*this);
#if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
beginTest ("Atomic int64");
AtomicTester <int64>::testInteger (*this);
beginTest ("Atomic uint64");
AtomicTester <uint64>::testInteger (*this);
beginTest ("Atomic double");
AtomicTester <double>::testFloat (*this);
#endif
beginTest ("Atomic pointer increment/decrement");
Atomic<int*> a (a2); int* b (a2);
expect (++a == ++b);
{
beginTest ("Atomic void*");
Atomic<void*> atomic;
void* c;
atomic.set ((void*) 10);
c = (void*) 10;
expect (atomic.value == c);
expect (atomic.get() == c);
}
}
template <typename Type>
class AtomicTester
{
public:
AtomicTester() = default;
static void testInteger (UnitTest& test)
{
Atomic<Type> a, b;
Type c;
a.set ((Type) 10);
c = (Type) 10;
test.expect (a.value == c);
test.expect (a.get() == c);
a += 15;
c += 15;
test.expect (a.get() == c);
a.memoryBarrier();
a -= 5;
c -= 5;
test.expect (a.get() == c);
test.expect (++a == ++c);
++a;
++c;
test.expect (--a == --c);
test.expect (a.get() == c);
a.memoryBarrier();
testFloat (test);
}
static void testFloat (UnitTest& test)
{
Atomic<Type> a, b;
a = (Type) 101;
a.memoryBarrier();
/* These are some simple test cases to check the atomics - let me know
if any of these assertions fail on your system!
*/
test.expect (exactlyEqual (a.get(), (Type) 101));
test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
test.expect (exactlyEqual (a.get(), (Type) 101));
test.expect (a.compareAndSetBool ((Type) 200, a.get()));
test.expect (exactlyEqual (a.get(), (Type) 200));
test.expect (exactlyEqual (a.exchange ((Type) 300), (Type) 200));
test.expect (exactlyEqual (a.get(), (Type) 300));
b = a;
test.expect (exactlyEqual (b.get(), a.get()));
}
};
};
static AtomicTests atomicUnitTests;
//==============================================================================
class ThreadLocalValueUnitTest final : public UnitTest,
private Thread
{
public:
ThreadLocalValueUnitTest()
: UnitTest ("ThreadLocalValue", UnitTestCategories::threads),
Thread (SystemStats::getJUCEVersion() + ": ThreadLocalValue Thread")
{}
void runTest() override
{
beginTest ("values are thread local");
{
ThreadLocalValue<int> threadLocal;
sharedThreadLocal = &threadLocal;
sharedThreadLocal.get()->get() = 1;
startThread();
signalThreadShouldExit();
waitForThreadToExit (-1);
mainThreadResult = sharedThreadLocal.get()->get();
expectEquals (mainThreadResult.get(), 1);
expectEquals (auxThreadResult.get(), 2);
}
beginTest ("values are per-instance");
{
ThreadLocalValue<int> a, b;
a.get() = 1;
b.get() = 2;
expectEquals (a.get(), 1);
expectEquals (b.get(), 2);
}
}
private:
Atomic<int> mainThreadResult, auxThreadResult;
Atomic<ThreadLocalValue<int>*> sharedThreadLocal;
void run() override
{
sharedThreadLocal.get()->get() = 2;
auxThreadResult = sharedThreadLocal.get()->get();
}
};
ThreadLocalValueUnitTest threadLocalValueUnitTest;
#endif
} // namespace juce
|