| 87 | } |
| 88 | |
| 89 | int mitkITKThreadingTest(int /*argc*/, char * /*argv*/ []) |
| 90 | { |
| 91 | itk::MultiThreader::Pointer threader = itk::MultiThreader::New(); |
| 92 | |
| 93 | int localInt(0); // this will be modified by both threads |
| 94 | |
| 95 | itk::Semaphore::Pointer m_ResultAvailable = itk::Semaphore::New(); |
| 96 | m_ResultAvailable->Initialize(0); // no pieces left (thread has to create one) |
| 97 | |
| 98 | itk::Semaphore::Pointer m_RunThreadRun = itk::Semaphore::New(); |
| 99 | m_RunThreadRun->Initialize(0); // no pieces left (thread has to create one) |
| 100 | |
| 101 | itk::FastMutexLock::Pointer m_Mutex = itk::FastMutexLock::New(); |
| 102 | |
| 103 | UserData userData; |
| 104 | userData.intPointer = &localInt; |
| 105 | userData.mutex = m_Mutex.GetPointer(); |
| 106 | userData.semaphore = m_ResultAvailable.GetPointer(); |
| 107 | userData.mayIRun = m_RunThreadRun.GetPointer(); |
| 108 | |
| 109 | itk::ThreadFunctionType pointer = &ThreadedFunction; |
| 110 | int thread_id = threader->SpawnThread(pointer, &userData); |
| 111 | |
| 112 | // let thread generate 10 results |
| 113 | for (int i = 1; i <= 10000; ++i) |
| 114 | m_ResultAvailable->Down(); |
| 115 | |
| 116 | std::cout << "signaling by semaphore thread->main "; |
| 117 | if (localInt == 10000) |
| 118 | std::cout << "[PASSED]" << std::endl; |
| 119 | else |
| 120 | { |
| 121 | std::cout << "[FAILED] localInt == " << localInt << std::endl; |
| 122 | return EXIT_FAILURE; |
| 123 | } |
| 124 | |
| 125 | // increase int simultaneously with thread (coordinated by mutex) |
| 126 | localInt = 0; |
| 127 | m_RunThreadRun->Up(); // let thread work again |
| 128 | for (int i = 1; i <= 10000; ++i) |
| 129 | { |
| 130 | m_Mutex->Lock(); |
| 131 | ++localInt; |
| 132 | m_Mutex->Unlock(); |
| 133 | } |
| 134 | |
| 135 | std::cout << "waiting for thread's signal" << std::endl; |
| 136 | ; |
| 137 | m_ResultAvailable->Down(); // wait for thread |
| 138 | std::cout << "got thread's signal" << std::endl; |
| 139 | ; |
| 140 | |
| 141 | std::cout << "sharing a mutex protected variable among threads"; |
| 142 | if (localInt == 20000) |
| 143 | std::cout << "[PASSED]" << std::endl; |
| 144 | else |
| 145 | { |
| 146 | std::cout << "[FAILED] localInt == " << localInt << std::endl; |
nothing calls this directly
no test coverage detected