NCBI C++ Toolkit Cross Reference

  C++/src/corelib/test_mt.cpp


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 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
/* $Id: test_mt.cpp 70460 2015-12-29 13:56:26Z ivanov $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * Wrapper for testing modules in MT environment * */ #include <ncbi_pch.hpp> #include <corelib/test_mt.hpp> #include <corelib/ncbimtx.hpp> #include <corelib/ncbi_system.hpp> #include <corelib/ncbi_param.hpp> #include <math.h> #include <common/test_assert.h> /* This header must go last */ BEGIN_NCBI_SCOPE // Uncomment the definition to use platform native threads rather // than CThread. //#define USE_NATIVE_THREADS DEFINE_STATIC_FAST_MUTEX(s_GlobalLock); static CThreadedApp* s_Application; // Default values unsigned int s_NumThreads = 34; int s_SpawnBy = 6; // Next test thread index static volatile unsigned int s_NextIndex = 0; #define TESTAPP_LOG_POST(x) do { ++m_LogMsgCount; LOG_POST(x); } while (0) ///////////////////////////////////////////////////////////////////////////// // Randomization parameters // if (rand() % 100 < threshold) then use cascading threads NCBI_PARAM_DECL(unsigned int, TEST_MT, Cascading); NCBI_PARAM_DEF(unsigned int, TEST_MT, Cascading, 25); // calculate # of thread groups static string s_GroupsCount(void) { return NStr::UIntToString( (unsigned int)sqrt((double)s_NumThreads)); } NCBI_PARAM_DECL(string, TEST_MT, GroupsCount); NCBI_PARAM_DEF_WITH_INIT(string, TEST_MT, GroupsCount, kEmptyStr, s_GroupsCount); // group.has_sync_point = (rand() % 100) < threshold; NCBI_PARAM_DECL(unsigned int, TEST_MT, IntragroupSyncPoint); NCBI_PARAM_DEF(unsigned int, TEST_MT, IntragroupSyncPoint, 75); ///////////////////////////////////////////////////////////////////////////// // Test thread // class CTestThread : public CThread { public: static void StartCascadingThreads(void); CTestThread(int id); virtual void SyncPoint(void) {}; virtual void GlobalSyncPoint(void); protected: ~CTestThread(void); virtual void* Main(void); virtual void OnExit(void); int m_Idx; #ifdef USE_NATIVE_THREADS TThreadHandle m_Handle; public: void RunNative(void); void JoinNative(void** result); friend TWrapperRes NativeWrapper(TWrapperArg arg); #endif }; static CSemaphore s_Semaphore(0, INT_MAX); /* For GlobalSyncPoint()*/ static CAtomicCounter s_SyncCounter; /* For GlobalSyncPoint()*/ static CAtomicCounter s_NumberOfThreads; /* For GlobalSyncPoint()*/ CTestThread::CTestThread(int idx) : m_Idx(idx) { /* We want to know total number of threads, and the easiest way is to make them register themselves */ s_NumberOfThreads.Add(1); if ( s_Application != 0 ) assert(s_Application->Thread_Init(m_Idx)); } CTestThread::~CTestThread(void) { s_NumberOfThreads.Add(-1); assert(s_NumberOfThreads.Get() >= 0); if ( s_Application != 0 ) assert(s_Application->Thread_Destroy(m_Idx)); } void CTestThread::OnExit(void) { if ( s_Application != 0 ) assert(s_Application->Thread_Exit(m_Idx)); } void CTestThread::GlobalSyncPoint(void) { /* Semaphore is supposed to have zero value when threads come here, so Wait() causes stop */ if (s_SyncCounter.Add(1) != s_NumberOfThreads.Get()) { s_Semaphore.Wait(); return; } /* If we are the last thread to come to sync point, we yield so that threads that were waiting for us go first */ if (s_NumberOfThreads.Get() > 1) { s_Semaphore.Post((unsigned int)s_NumberOfThreads.Get() - 1); s_SyncCounter.Set(0); SleepMilliSec(0); } } #ifdef USE_NATIVE_THREADS TWrapperRes NativeWrapper(TWrapperArg arg) { CTestThread* thread_obj = static_cast<CTestThread*>(arg); thread_obj->Main(); return 0; } #if defined(NCBI_POSIX_THREADS) extern "C" { typedef TWrapperRes (*FSystemWrapper)(TWrapperArg); static TWrapperRes NativeWrapperCaller(TWrapperArg arg) { return NativeWrapper(arg); } } #elif defined(NCBI_WIN32_THREADS) extern "C" { typedef TWrapperRes (WINAPI *FSystemWrapper)(TWrapperArg); static TWrapperRes WINAPI NativeWrapperCaller(TWrapperArg arg) { return NativeWrapper(arg); } } #endif void CTestThread::RunNative(void) { // Run as the platform native thread rather than CThread // Not all functionality will work in this mode. E.g. TLS // cleanup can not be done automatically. #if defined(NCBI_WIN32_THREADS) // We need this parameter on WinNT - cannot use NULL instead! DWORD thread_id; // Suspend thread to adjust its priority DWORD creation_flags = 0; m_Handle = CreateThread(NULL, 0, NativeWrapperCaller, this, creation_flags, &thread_id); _ASSERT(m_Handle != NULL); // duplicate handle to adjust security attributes HANDLE oldHandle = m_Handle; _ASSERT(DuplicateHandle(GetCurrentProcess(), oldHandle, GetCurrentProcess(), &m_Handle, 0, FALSE, DUPLICATE_SAME_ACCESS)); _ASSERT(CloseHandle(oldHandle)); #elif defined(NCBI_POSIX_THREADS) pthread_attr_t attr; _ASSERT(pthread_attr_init(&attr) == 0); _ASSERT(pthread_create(&m_Handle, &attr, NativeWrapperCaller, this) == 0); _ASSERT(pthread_attr_destroy(&attr) == 0); #else if (flags & fRunAllowST) { Wrapper(this); } else { _ASSERT(0); } #endif } void CTestThread::JoinNative(void** result) { // Join (wait for) and destroy #if defined(NCBI_WIN32_THREADS) _ASSERT(WaitForSingleObject(m_Handle, INFINITE) == WAIT_OBJECT_0); DWORD status; _ASSERT(GetExitCodeThread(m_Handle, &status) && status != DWORD(STILL_ACTIVE)); _ASSERT(CloseHandle(m_Handle)); m_Handle = NULL; #elif defined(NCBI_POSIX_THREADS) _ASSERT(pthread_join(m_Handle, 0) == 0); #endif *result = this; } #endif // USE_NATIVE_THREADS CRef<CTestThread> thr[k_NumThreadsMax]; void CTestThread::StartCascadingThreads(void) { int spawn_max; int first_idx; {{ CFastMutexGuard spawn_guard(s_GlobalLock); spawn_max = s_NumThreads - s_NextIndex; if (spawn_max > s_SpawnBy) { spawn_max = s_SpawnBy; } first_idx = s_NextIndex; s_NextIndex += s_SpawnBy; }} // Spawn more threads for (int i = first_idx; i < first_idx + spawn_max; i++) { thr[i] = new CTestThread(i); // Allow threads to run even in single thread environment #ifdef USE_NATIVE_THREADS thr[i]->RunNative(); #else thr[i]->Run(CThread::fRunAllowST); #endif } } void* CTestThread::Main(void) { StartCascadingThreads(); // Run the test if ( s_Application != 0 && s_Application->Thread_Run(m_Idx) ) { return this; } return 0; } ///////////////////////////////////////////////////////////////////////////// // Thread group class CThreadGroup; class CInGroupThread : public CTestThread { public: CInGroupThread(CThreadGroup& group, int id); virtual void SyncPoint(void); protected: ~CInGroupThread(void); virtual void* Main(void); CThreadGroup& m_Group; }; class CThreadGroup : public CObject { public: CThreadGroup( unsigned int number_of_threads, bool has_sync_point); ~CThreadGroup(void); void Go(void); void SyncPoint(void); void ThreadWait(void); void ThreadComplete(void); private: unsigned int m_Number_of_threads; bool m_Has_sync_point; CSemaphore m_Semaphore; CFastMutex m_Mutex; unsigned int m_SyncCounter; }; static CRef<CThreadGroup> thr_group[k_NumThreadsMax]; static CStaticTls<int> s_ThreadIdxTLS; CInGroupThread::CInGroupThread(CThreadGroup& group, int id) : CTestThread(id), m_Group(group) { } CInGroupThread::~CInGroupThread(void) { } void CInGroupThread::SyncPoint(void) { m_Group.SyncPoint(); } void* CInGroupThread::Main(void) { m_Group.ThreadWait(); s_ThreadIdxTLS.SetValue(reinterpret_cast<int*>(m_Idx)); // Run the test if ( s_Application != 0 && s_Application->Thread_Run(m_Idx) ) { m_Group.ThreadComplete(); return this; } return 0; } CThreadGroup::CThreadGroup( unsigned int number_of_threads, bool has_sync_point) : m_Number_of_threads(number_of_threads), m_Has_sync_point(has_sync_point), m_Semaphore(0,number_of_threads), m_SyncCounter(0) { for (unsigned int t = 0; t < m_Number_of_threads; ++t) { thr[s_NextIndex] = new CInGroupThread(*this, s_NextIndex); #ifdef USE_NATIVE_THREADS thr[s_NextIndex]->RunNative(); #else thr[s_NextIndex]->Run(); #endif ++s_NextIndex; } } CThreadGroup::~CThreadGroup(void) { } inline void CThreadGroup::Go(void) { s_NumberOfThreads.Add(m_Number_of_threads); m_Semaphore.Post(m_Number_of_threads); } void CThreadGroup::SyncPoint(void) { if (m_Has_sync_point) { bool reached = false; m_Mutex.Lock(); ++m_SyncCounter; if (m_SyncCounter == m_Number_of_threads) { m_SyncCounter = 0; reached = true; } m_Mutex.Unlock(); if (reached) { if (m_Number_of_threads > 1) { m_Semaphore.Post(m_Number_of_threads-1); SleepMilliSec(0); } } else { m_Semaphore.Wait(); } } } inline void CThreadGroup::ThreadWait(void) { s_NumberOfThreads.Add(-1); assert(s_NumberOfThreads.Get() >= 0); m_Semaphore.Wait(); } inline void CThreadGroup::ThreadComplete(void) { if (m_Has_sync_point) { m_Semaphore.Post(); } } ///////////////////////////////////////////////////////////////////////////// // Test application CThreadedApp::CThreadedApp(void) { m_Min = m_Max = 0; m_NextGroup = 0; m_LogMsgCount = 0; s_Application = this; CThread::InitializeMainThreadId(); } CThreadedApp::~CThreadedApp(void) { s_Application = 0; } void CThreadedApp::Init(void) { // Prepare command line descriptions auto_ptr<CArgDescriptions> arg_desc(new CArgDescriptions); // s_NumThreads arg_desc->AddDefaultKey ("threads", "NumThreads", "Total number of threads to create and run", CArgDescriptions::eInteger, NStr::IntToString(s_NumThreads)); arg_desc->SetConstraint ("threads", new CArgAllow_Integers(k_NumThreadsMin, k_NumThreadsMax)); // s_NumThreads (emulation in ST) arg_desc->AddDefaultKey ("repeats", "NumRepeats", "In non-MT mode only(!) -- how many times to repeat the test. " "If passed 0, then the value of argument `-threads' will be used.", CArgDescriptions::eInteger, "0"); arg_desc->SetConstraint ("repeats", new CArgAllow_Integers(0, k_NumThreadsMax)); // s_SpawnBy arg_desc->AddDefaultKey ("spawnby", "SpawnBy", "Threads spawning factor", CArgDescriptions::eInteger, NStr::IntToString(s_SpawnBy)); arg_desc->SetConstraint ("spawnby", new CArgAllow_Integers(k_SpawnByMin, k_SpawnByMax)); arg_desc->AddOptionalKey("seed", "Randomization", "Randomization seed value", CArgDescriptions::eInteger); arg_desc->SetUsageContext(GetArguments().GetProgramBasename(), "MT-environment test"); // Let test application add its own arguments TestApp_Args(*arg_desc); SetupArgDescriptions(arg_desc.release()); } int CThreadedApp::Run(void) { // Process command line const CArgs& args = GetArgs(); #if !defined(NCBI_THREADS) s_NumThreads = args["repeats"].AsInteger(); if ( !s_NumThreads ) #endif s_NumThreads = args["threads"].AsInteger(); #if !defined(NCBI_THREADS) // Set reasonable repeats if not set through the argument if (!args["repeats"].AsInteger()) { unsigned int repeats = s_NumThreads / 6; if (repeats < 4) repeats = 4; if (repeats < s_NumThreads) s_NumThreads = repeats; } #endif s_SpawnBy = args["spawnby"].AsInteger(); assert(TestApp_Init()); unsigned int seed = GetArgs()["seed"] ? static_cast<unsigned int>(GetArgs()["seed"].AsInteger()) : (static_cast<unsigned int>(CProcess::GetCurrentPid()) ^ static_cast<unsigned int>(time(NULL)) % 1000000); TESTAPP_LOG_POST("Randomization seed value: " << seed); srand(seed); unsigned int threshold = NCBI_PARAM_TYPE(TEST_MT, Cascading)::GetDefault(); if (threshold > 100) { ERR_FATAL("Cascading threshold must be less than 100"); } bool cascading = (static_cast<unsigned int>(rand() % 100)) < threshold; #if !defined(NCBI_THREADS) cascading = true; #endif if ( !cascading ) { x_InitializeThreadGroups(); x_PrintThreadGroups(); } cascading = cascading || (m_ThreadGroups.size() == 0); #if defined(NCBI_THREADS) TESTAPP_LOG_POST("Running " << s_NumThreads << " threads"); #else TESTAPP_LOG_POST("Simulating " << s_NumThreads << " threads in ST mode"); #endif if (cascading) { CTestThread::StartCascadingThreads(); } else { unsigned int start_now = x_InitializeDelayedStart(); for (unsigned int g = 0; g < m_ThreadGroups.size(); ++g) { thr_group[g] = new CThreadGroup (m_ThreadGroups[g].number_of_threads, m_ThreadGroups[g].has_sync_point); } x_StartThreadGroup(start_now); } // Wait for all threads if ( cascading ) { for (unsigned int i = 0; i < s_NumThreads; i++) { void* ok; // make sure all threads have started assert(thr[i].NotEmpty()); #ifdef USE_NATIVE_THREADS if (thr[i]) { thr[i]->JoinNative(&ok); assert(ok); } #else thr[i]->Join(&ok); assert(ok); #endif } } else { // join only those that started unsigned int i = 0; for (unsigned int g = 0; g < m_NextGroup; ++g) { for (unsigned int t = 0; t < m_ThreadGroups[g].number_of_threads; ++t, ++i) { void* ok; thr[i]->Join(&ok); assert(ok); } } assert(m_Reached.size() >= m_Min); } assert(TestApp_Exit()); // Destroy all threads for (unsigned int i=0; i<s_NumThreads; i++) { thr[i].Reset(); } // Destroy all groups for (unsigned int i=0; i<m_ThreadGroups.size(); i++) { thr_group[i].Reset(); } return 0; } void CThreadedApp::x_InitializeThreadGroups(void) { unsigned int count = NStr::StringToUInt (NCBI_PARAM_TYPE(TEST_MT, GroupsCount)::GetDefault()); if (count == 0) { return; } if(count > s_NumThreads) { ERR_FATAL("Thread groups with no threads are not allowed"); } unsigned int threshold = NCBI_PARAM_TYPE(TEST_MT, IntragroupSyncPoint)::GetDefault(); if (threshold > 100) { ERR_FATAL("IntragroupSyncPoint threshold must be less than 100"); } for (unsigned int g = 0; g < count; ++g) { SThreadGroup group; // randomize intra-group sync points group.has_sync_point = ((unsigned int)(rand() % 100)) < threshold; group.number_of_threads = 1; m_ThreadGroups.push_back(group); } if (s_NumThreads > count) { unsigned int threads_left = s_NumThreads - count; for (unsigned int t = 0; t < threads_left; ++t) { // randomize # of threads m_ThreadGroups[ rand() % count ].number_of_threads += 1; } } } void CThreadedApp::x_PrintThreadGroups( void) { size_t count = m_ThreadGroups.size(); if (count != 0) { TESTAPP_LOG_POST("Thread groups: " << count); TESTAPP_LOG_POST("Number of delayed thread groups: from " << m_Min << " to " << m_Max); TESTAPP_LOG_POST("------------------------"); TESTAPP_LOG_POST("group threads sync_point"); for (unsigned int g = 0; g < count; ++g) { CNcbiOstrstream os; os.width(6); os << left << g; os.width(8); os << left << m_ThreadGroups[g].number_of_threads; if (m_ThreadGroups[g].has_sync_point) { os << "yes"; } else { os << "no "; } TESTAPP_LOG_POST(string(CNcbiOstrstreamToString(os))); } TESTAPP_LOG_POST("------------------------"); } } unsigned int CThreadedApp::x_InitializeDelayedStart(void) { const unsigned int count = static_cast<unsigned int>(m_ThreadGroups.size()); unsigned int start_now = count; unsigned int g; if (m_Max == 0) return start_now; for (g = 0; g < m_Max; ++g) { m_Delayed.push_back(0); } for (g = 1; g < count; ++g) { unsigned int dest = rand() % (m_Max+1); if (dest != 0) { m_Delayed[dest - 1] += 1; --start_now; } } CNcbiOstrstream os; os << "Delayed thread groups: " << (count - start_now) << ", starting order: " << start_now; for (g = 0; g < m_Max; ++g) { os << '+' << m_Delayed[g]; } TESTAPP_LOG_POST(string(CNcbiOstrstreamToString(os))); return start_now; } void CThreadedApp::x_StartThreadGroup(unsigned int count) { CFastMutexGuard LOCK(m_AppMutex); while (count--) { thr_group[m_NextGroup++]->Go(); } } ///////////////////////////////////////////////////////////////////////////// bool CThreadedApp::Thread_Init(int /*idx*/) { return true; } bool CThreadedApp::Thread_Run(int /*idx*/) { return true; } bool CThreadedApp::Thread_Exit(int /*idx*/) { return true; } bool CThreadedApp::Thread_Destroy(int /*idx*/) { return true; } bool CThreadedApp::TestApp_Args(CArgDescriptions& /*args*/) { return true; } bool CThreadedApp::TestApp_Init(void) { return true; } void CThreadedApp::TestApp_IntraGroupSyncPoint(void) { int idx = (int)(intptr_t(s_ThreadIdxTLS.GetValue())); thr[idx]->SyncPoint(); } void CThreadedApp::TestApp_GlobalSyncPoint(void) { {{ CFastMutexGuard LOCK(m_AppMutex); if (!m_Delayed.empty()) { TESTAPP_LOG_POST("There were delayed threads, running them now, " "because TestApp_GlobalSyncPoint() was called"); for (size_t i = m_Reached.size(); i < m_Delayed.size(); i++) { m_Reached.insert(NStr::SizetToString(i)); x_StartThreadGroup(m_Delayed[i]); } } }} int idx = static_cast<int>(intptr_t(s_ThreadIdxTLS.GetValue())); thr[idx]->GlobalSyncPoint(); } void CThreadedApp::SetNumberOfDelayedStartSyncPoints( unsigned int num_min, unsigned int num_max) { m_Min = num_min; m_Max = num_max; } void CThreadedApp::TestApp_DelayedStartSyncPoint(const string& name) { CFastMutexGuard LOCK(m_AppMutex); if (!m_Delayed.empty() && m_Reached.find(name) == m_Reached.end()) { m_Reached.insert(name); if (m_Reached.size() <= m_Delayed.size()) { x_StartThreadGroup(m_Delayed[m_Reached.size() - 1]); } } } bool CThreadedApp::TestApp_Exit(void) { return true; } END_NCBI_SCOPE

source navigation ]   [ diff markup ]   [ identifier search ]   [ freetext search ]   [ file search ]  

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.