| 1 | |
| 2 | // Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide. |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, |
| 6 | // are permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, |
| 9 | // this list of conditions, and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, |
| 12 | // this list of conditions, and the following disclaimer in the documentation |
| 13 | // and/or other materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the names of the copyright holders nor the names of their contributors |
| 16 | // may be used to endorse or promote products derived from this software without |
| 17 | // specific prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT |
| 24 | // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
| 25 | // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR |
| 26 | // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 27 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS |
| 28 | // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES |
| 29 | // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE |
| 30 | // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES. |
| 31 | // |
| 32 | |
| 33 | #include "threading.h" |
| 34 | #include <signal.h> |
| 35 | #include <time.h> |
| 36 | #include <xstypes/xstime.h> |
| 37 | |
| 38 | #ifdef __GNUC__ |
| 39 | #include <sys/time.h> |
| 40 | #include <signal.h> |
| 41 | #include <fcntl.h> |
| 42 | #include <sys/stat.h> |
| 43 | #define _strdup strdup |
| 44 | #endif |
| 45 | |
| 46 | namespace xsens { |
| 47 | #ifdef __GNUC__ |
| 48 | pthread_t xsStartThread(void *(func)(void *), void *param, void *pid) { |
| 49 | return ::xsStartThread(func, param, pid); |
| 50 | } |
| 51 | #endif |
| 52 | |
| 53 | /*! Constructor, creates the necessary signals. Does NOT start the thread. |
| 54 | */ |
| 55 | StandardThread::StandardThread() |
| 56 | : m_thread(XSENS_INVALID_THREAD) |
| 57 | , m_priority(XS_THREAD_PRIORITY_NORMAL) |
| 58 | , m_stop(false) |
| 59 | , m_yieldOnZeroSleep(true) |
| 60 | #ifdef _WIN32 |
| 61 | , m_stopHandle(::CreateEvent(NULL,TRUE,FALSE,NULL)) |
| 62 | , m_running(::CreateEvent(NULL,TRUE,FALSE,NULL)) |
| 63 | , m_threadId(0) |
| 64 | #else |
| 65 | , m_running(false) |
| 66 | #endif |
| 67 | , m_name(NULL) |
| 68 | { |
| 69 | #ifndef _WIN32 |
| 70 | pthread_attr_init(&m_attr); |
| 71 | #endif |
| 72 | } |
| 73 | |
| 74 | /*! Destructor, stops the thread if it was running and cleans up afterwards. |
| 75 | */ |
| 76 | StandardThread::~StandardThread() |
| 77 | { |
| 78 | stopThread(); |
| 79 | |
| 80 | if (m_name) |
| 81 | { |
| 82 | free(m_name); |
| 83 | m_name = NULL; |
| 84 | } |
| 85 | |
| 86 | #ifdef _WIN32 |
| 87 | ::CloseHandle(m_running); |
| 88 | ::CloseHandle(m_stopHandle); |
| 89 | #else |
| 90 | pthread_attr_destroy(&m_attr); |
| 91 | #endif |
| 92 | } |
| 93 | |
| 94 | #ifdef _WIN32 |
| 95 | /*! \brief Kill the thread now */ |
| 96 | void StandardThread::terminateThread() |
| 97 | { |
| 98 | if (m_thread != XSENS_INVALID_THREAD) |
| 99 | ::TerminateThread(m_thread, DWORD(-1)); |
| 100 | m_thread = XSENS_INVALID_THREAD; |
| 101 | } |
| 102 | #endif |
| 103 | |
| 104 | /*! \returns True if the thread is alive |
| 105 | */ |
| 106 | bool StandardThread::isAlive(void) volatile const noexcept |
| 107 | { |
| 108 | if (m_thread == XSENS_INVALID_THREAD) |
| 109 | return false; |
| 110 | |
| 111 | #ifdef _WIN32 |
| 112 | DWORD exitCode; |
| 113 | if (::GetExitCodeThread(m_thread,&exitCode)) |
| 114 | { |
| 115 | if (exitCode == STILL_ACTIVE) |
| 116 | return true; |
| 117 | } |
| 118 | return false; |
| 119 | #else |
| 120 | return (pthread_kill(m_thread, 0) == 0); |
| 121 | #endif |
| 122 | } |
| 123 | |
| 124 | /*! \brief Returns whether the thread is currently running. |
| 125 | */ |
| 126 | bool StandardThread::isRunning(void) volatile const noexcept |
| 127 | { |
| 128 | if (!isAlive()) |
| 129 | return false; |
| 130 | #ifdef _WIN32 |
| 131 | switch(::WaitForSingleObject(m_running,0)) |
| 132 | { |
| 133 | case WAIT_ABANDONED: |
| 134 | case WAIT_TIMEOUT: |
| 135 | return false; |
| 136 | case WAIT_OBJECT_0: |
| 137 | return true; |
| 138 | default: |
| 139 | return false; |
| 140 | } |
| 141 | #else |
| 142 | return m_running; |
| 143 | #endif |
| 144 | } |
| 145 | |
| 146 | /*! \brief Returns whether the thread should (have) terminate(d) |
| 147 | */ |
| 148 | bool StandardThread::isTerminating(void) volatile const noexcept |
| 149 | { |
| 150 | return m_stop; |
| 151 | } |
| 152 | |
| 153 | /*! \brief Sets the priority of the thread |
| 154 | \param pri The thread priority to set |
| 155 | \return True if successful |
| 156 | */ |
| 157 | bool StandardThread::setPriority(XsThreadPriority pri) |
| 158 | { |
| 159 | m_priority = pri; |
| 160 | |
| 161 | if (!isAlive()) |
| 162 | return false; |
| 163 | |
| 164 | #ifdef _WIN32 |
| 165 | ::SetThreadPriority(m_thread, (int) pri); |
| 166 | #else |
| 167 | #ifdef _POSIX_PRIORITY_SCHEDULING |
| 168 | int32_t rv; |
| 169 | int32_t policy; |
| 170 | struct sched_param param; |
| 171 | |
| 172 | if (!isAlive()) |
| 173 | return false; |
| 174 | |
| 175 | rv = pthread_getschedparam(m_thread, &policy, ¶m); |
| 176 | switch (rv) |
| 177 | { |
| 178 | case ESRCH: |
| 179 | /* The value specified by thread does not refer to an existing thread. */ |
| 180 | return false; |
| 181 | default: |
| 182 | break; |
| 183 | } |
| 184 | |
| 185 | switch (pri) { |
| 186 | case XS_THREAD_PRIORITY_HIGHEST: |
| 187 | param.sched_priority = sched_get_priority_max(policy); |
| 188 | break; |
| 189 | |
| 190 | case XS_THREAD_PRIORITY_LOWEST: |
| 191 | param.sched_priority = sched_get_priority_max(policy); |
| 192 | // Fallthrough. |
| 193 | default: |
| 194 | /* we need to map the priority to the values used on this system */ |
| 195 | int32_t min_prio = sched_get_priority_min(policy); |
| 196 | int32_t max_prio = sched_get_priority_max(policy); |
| 197 | |
| 198 | if (min_prio < 0 || max_prio < 0) |
| 199 | return false; |
| 200 | |
| 201 | /* divide range up in amount of priority levels */ |
| 202 | float priostep = ((float)(max_prio - min_prio)) / ((int32_t)XS_THREAD_PRIORITY_HIGHEST + 1); |
| 203 | |
| 204 | param.sched_priority = (int32_t) (min_prio + (pri * priostep)); |
| 205 | break; |
| 206 | } |
| 207 | |
| 208 | rv = pthread_setschedparam(m_thread, policy, ¶m); |
| 209 | switch (rv) |
| 210 | { |
| 211 | case ESRCH: |
| 212 | /* The value specified by thread does not refer to an existing thread. */ |
| 213 | case EINVAL: |
| 214 | /* The value specified by policy or one of the scheduling parameters |
| 215 | * associated with the scheduling policy policy is invalid. |
| 216 | */ |
| 217 | case ENOTSUP: |
| 218 | /* An attempt was made to set the policy or scheduling parameters to an |
| 219 | * unsupported value. |
| 220 | * An attempt was made to dynamically change the scheduling policy to |
| 221 | * SCHED_SPORADIC, and the implementation does not support this change. |
| 222 | */ |
| 223 | case EPERM: |
| 224 | /* The caller does not have the appropriate permission to set either the |
| 225 | * scheduling parameters or the scheduling policy of the specified thread. |
| 226 | * The implementation does not allow the application to modify one of the |
| 227 | * parameters to the value specified. |
| 228 | */ |
| 229 | return false; |
| 230 | default: |
| 231 | break; |
| 232 | } |
| 233 | |
| 234 | return true; |
| 235 | #else |
| 236 | return true; |
| 237 | #endif |
| 238 | #endif |
| 239 | return true; |
| 240 | } |
| 241 | |
| 242 | /*! \brief Starts the thread |
| 243 | \param name The name of the thread as shown in the debugger, may be NULL in which case the system determines the name. |
| 244 | \returns True if successful |
| 245 | */ |
| 246 | bool StandardThread::startThread(const char* name) |
| 247 | { |
| 248 | if (isAlive()) |
| 249 | return false; |
| 250 | |
| 251 | if (m_name) |
| 252 | free(m_name); |
| 253 | if (name) |
| 254 | m_name = _strdup(name); |
| 255 | else |
| 256 | m_name = NULL; |
| 257 | |
| 258 | #ifdef _WIN32 |
| 259 | m_stop = false; |
| 260 | ::ResetEvent(m_stopHandle); |
| 261 | ::SetEvent(m_running); |
| 262 | m_thread = xsStartThread(&threadInit,this,&m_threadId); |
| 263 | if (m_thread == XSENS_INVALID_THREAD) |
| 264 | { |
| 265 | ::ResetEvent(m_running); |
| 266 | return false; |
| 267 | } |
| 268 | #else |
| 269 | m_stop = false; |
| 270 | m_running = true; |
| 271 | if (pthread_create(&m_thread, &m_attr, threadInit, this)) |
| 272 | { |
| 273 | /* something went wrong */ |
| 274 | m_thread = XSENS_INVALID_THREAD; |
| 275 | return false; |
| 276 | } |
| 277 | #endif |
| 278 | xsSetThreadPriority(m_thread, m_priority); |
| 279 | |
| 280 | return true; |
| 281 | } |
| 282 | |
| 283 | /*! \brief Tells the thread to stop but does not wait for it to end. |
| 284 | */ |
| 285 | void StandardThread::signalStopThread(void) |
| 286 | { |
| 287 | #ifdef _WIN32 |
| 288 | m_stop = true; |
| 289 | ::SetEvent(m_stopHandle); |
| 290 | ::SetThreadPriority(m_thread, THREAD_PRIORITY_ABOVE_NORMAL); |
| 291 | #else |
| 292 | setPriority(XS_THREAD_PRIORITY_HIGHEST); |
| 293 | m_stop = true; |
| 294 | #endif |
| 295 | } |
| 296 | |
| 297 | /*! \brief Tells the thread to stop and waits for it to end. |
| 298 | */ |
| 299 | void StandardThread::stopThread(void) noexcept |
| 300 | { |
| 301 | #ifdef _WIN32 |
| 302 | // prevent multiple threads from doing this at the same time on windows, pthreads deals with this in its own special way |
| 303 | xsens::Lock locky(&m_mux, false); |
| 304 | if (m_threadId == xsGetCurrentThreadId()) |
| 305 | locky.tryLock(); |
| 306 | else |
| 307 | locky.lock(); |
| 308 | #endif |
| 309 | |
| 310 | if (!isAlive()) |
| 311 | return; |
| 312 | |
| 313 | signalStopThread(); |
| 314 | #ifdef _WIN32 |
| 315 | // don't wait for my thread to end myself |
| 316 | if (m_threadId == xsGetCurrentThreadId()) |
| 317 | return; |
| 318 | |
| 319 | // in debug mode we ALWAYS want to know if there's some kind of deadlock occurring |
| 320 | //#if XSENS_THREAD_KILL_TIMEOUT_MS > 0 && !defined(XSENS_DEBUG) |
| 321 | // XsTimeStamp endOfWait = XsTimeStamp::now() + XSENS_THREAD_KILL_TIMEOUT_MS; |
| 322 | // while(isAlive() && (XsTimeStamp::now() < endOfWait)) |
| 323 | // xsYield(); |
| 324 | //#else |
| 325 | |
| 326 | while (isAlive()) |
| 327 | xsYield(); |
| 328 | //#endif |
| 329 | if (m_thread != XSENS_INVALID_THREAD && ::CloseHandle(m_thread) == 0) |
| 330 | { |
| 331 | DWORD lastErr = GetLastError(); |
| 332 | (void)lastErr; |
| 333 | return; |
| 334 | } |
| 335 | #else |
| 336 | // don't wait for my thread to end myself |
| 337 | if (pthread_equal(m_thread, xsGetCurrentThreadId())) |
| 338 | return; |
| 339 | |
| 340 | // in debug mode we ALWAYS want to know if there's some kind of deadlock occurring |
| 341 | //#if XSENS_THREAD_KILL_TIMEOUT_MS > 0 && !defined(XSENS_DEBUG) |
| 342 | // XsTimeStamp endOfWait = XsTimeStamp::now() + XSENS_THREAD_KILL_TIMEOUT_MS; |
| 343 | // while(isAlive() && (XsTimeStamp::now() < endOfWait)) |
| 344 | // xsYield(); |
| 345 | |
| 346 | // if (isAlive()) { |
| 347 | // if (pthread_kill(m_thread, 9)) |
| 348 | // return; |
| 349 | // } |
| 350 | //#else |
| 351 | while (isAlive()) |
| 352 | xsYield(); |
| 353 | //#endif |
| 354 | if (pthread_join(m_thread, NULL)) |
| 355 | { |
| 356 | switch (errno) |
| 357 | { |
| 358 | case EINVAL: |
| 359 | /* no joinable thread found */ |
| 360 | case ESRCH: |
| 361 | /* no thread fits thread id */ |
| 362 | case EDEADLK: |
| 363 | /* deadlock or trying to join self */ |
| 364 | default: |
| 365 | break; |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | m_running = false; |
| 370 | #endif |
| 371 | m_thread = XSENS_INVALID_THREAD; |
| 372 | } |
| 373 | |
| 374 | XSENS_THREAD_RETURN StandardThread::threadInit(void* obj) |
| 375 | { |
| 376 | StandardThread* thread = reinterpret_cast<StandardThread*>(obj); |
| 377 | if (thread->m_name) |
| 378 | xsNameThisThread(thread->m_name); |
| 379 | |
| 380 | thread->threadMain(); |
| 381 | return 0; |
| 382 | } |
| 383 | |
| 384 | #ifndef _WIN32 |
| 385 | /*! \brief Cleanup the thread by calling the exit function */ |
| 386 | void StandardThread::threadCleanup(void *obj) |
| 387 | { |
| 388 | ((StandardThread *)obj)->exitFunction(); |
| 389 | } |
| 390 | #endif |
| 391 | |
| 392 | /*! \brief The inner loop of the thread, calls innerFunction repeatedly and sleeps when necessary |
| 393 | */ |
| 394 | void StandardThread::threadMain(void) |
| 395 | { |
| 396 | initFunction(); |
| 397 | bool go = true; |
| 398 | while (go) |
| 399 | { |
| 400 | int32_t rv = innerFunction(); |
| 401 | if (m_stop) |
| 402 | go = false; |
| 403 | else if (rv > 0) |
| 404 | { |
| 405 | int64_t sleepStart = XsTimeStamp::nowMs(); |
| 406 | while (!m_stop) |
| 407 | { |
| 408 | // sleep max 100ms at a time so we can terminate the thread quickly if necessary |
| 409 | int64_t timePassed = XsTimeStamp::nowMs()-sleepStart; |
| 410 | int32_t remaining = rv - (int32_t) timePassed; |
| 411 | if (remaining > 100) |
| 412 | XsTime::msleep(100); |
| 413 | else if (remaining <= 0) |
| 414 | break; |
| 415 | else |
| 416 | XsTime::msleep((uint32_t) remaining); |
| 417 | } |
| 418 | if (m_stop) |
| 419 | go = false; |
| 420 | } |
| 421 | else if (m_yieldOnZeroSleep) |
| 422 | xsYield(); |
| 423 | } |
| 424 | exitFunction(); |
| 425 | } |
| 426 | |
| 427 | ////////////////////////////////////////////////////////////////////////////////////////// |
| 428 | ////////////////////////////////////////////////////////////////////////////////////////// |
| 429 | ////////////////////////////////////////////////////////////////////////////////////////// |
| 430 | |
| 431 | WatchDogThread::WatchDogThread(WatchDogFunction func, void* param) |
| 432 | : m_thread(XSENS_INVALID_THREAD) |
| 433 | #ifdef _WIN32 |
| 434 | , m_stop(::CreateEvent(NULL,TRUE,FALSE,NULL)) |
| 435 | , m_running(::CreateEvent(NULL,TRUE,FALSE,NULL)) |
| 436 | , m_reset(::CreateEvent(NULL,TRUE,FALSE,NULL)) |
| 437 | #else |
| 438 | , m_running(false) |
| 439 | , m_reset(false) |
| 440 | , m_stop(false) |
| 441 | #endif |
| 442 | , m_timeout(10000) |
| 443 | , m_func(func) |
| 444 | , m_param(param) |
| 445 | , m_name(NULL) |
| 446 | , m_threadId(0) |
| 447 | { |
| 448 | #ifndef _WIN32 |
| 449 | pthread_attr_init(&m_attr); |
| 450 | #endif |
| 451 | } |
| 452 | |
| 453 | WatchDogThread::~WatchDogThread() |
| 454 | { |
| 455 | stopTimer(); |
| 456 | |
| 457 | if (m_name) |
| 458 | { |
| 459 | free(m_name); |
| 460 | m_name = NULL; |
| 461 | } |
| 462 | |
| 463 | #ifdef _WIN32 |
| 464 | ::CloseHandle(m_reset); |
| 465 | ::CloseHandle(m_running); |
| 466 | ::CloseHandle(m_stop); |
| 467 | #else |
| 468 | pthread_attr_destroy(&m_attr); |
| 469 | #endif |
| 470 | } |
| 471 | |
| 472 | bool WatchDogThread::isAlive(void) volatile const noexcept |
| 473 | { |
| 474 | #ifdef _WIN32 |
| 475 | DWORD exitCode; |
| 476 | if (::GetExitCodeThread(m_thread,&exitCode)) |
| 477 | return (exitCode == STILL_ACTIVE); |
| 478 | #else |
| 479 | if (m_thread == XSENS_INVALID_THREAD) |
| 480 | return false; |
| 481 | |
| 482 | return (pthread_kill(m_thread, 0) == 0); |
| 483 | #endif |
| 484 | return false; |
| 485 | } |
| 486 | |
| 487 | bool WatchDogThread::isRunning(void) volatile const noexcept |
| 488 | { |
| 489 | if (!isAlive()) |
| 490 | return false; |
| 491 | #ifdef _WIN32 |
| 492 | switch(::WaitForSingleObject(m_running,0)) |
| 493 | { |
| 494 | case WAIT_ABANDONED: |
| 495 | case WAIT_TIMEOUT: |
| 496 | return false; |
| 497 | case WAIT_OBJECT_0: |
| 498 | switch(::WaitForSingleObject(m_stop,0)) |
| 499 | { |
| 500 | case WAIT_ABANDONED: |
| 501 | case WAIT_TIMEOUT: |
| 502 | return true; |
| 503 | case WAIT_OBJECT_0: |
| 504 | return false; |
| 505 | default: |
| 506 | return false; |
| 507 | } |
| 508 | default: |
| 509 | return false; |
| 510 | } |
| 511 | #else |
| 512 | return m_running; |
| 513 | #endif |
| 514 | } |
| 515 | |
| 516 | /*! \brief Starts a timer using some parameters |
| 517 | \param timeout The timeout value to use |
| 518 | \param name The name of a thread to set |
| 519 | \returns True if successful |
| 520 | */ |
| 521 | bool WatchDogThread::startTimer(uint32_t timeout, const char* name) |
| 522 | { |
| 523 | if (isAlive()) |
| 524 | return false; |
| 525 | |
| 526 | if (timeout != 0) |
| 527 | m_timeout = timeout; |
| 528 | |
| 529 | if (m_name) |
| 530 | free(m_name); |
| 531 | if (name) |
| 532 | m_name = _strdup(name); |
| 533 | else |
| 534 | m_name = NULL; |
| 535 | |
| 536 | #ifdef _WIN32 |
| 537 | ::ResetEvent(m_stop); |
| 538 | ::SetEvent(m_running); |
| 539 | ::ResetEvent(m_reset); |
| 540 | m_thread = xsStartThread(&threadInit,this,&m_threadId); |
| 541 | if (m_thread == XSENS_INVALID_THREAD) |
| 542 | { |
| 543 | ::ResetEvent(m_running); |
| 544 | return false; |
| 545 | } |
| 546 | |
| 547 | #else |
| 548 | m_running = true; |
| 549 | m_reset = false; |
| 550 | m_stop = false; |
| 551 | |
| 552 | if (pthread_create(&m_thread, &m_attr, threadInit, this) != 0) |
| 553 | return false; |
| 554 | #endif |
| 555 | return true; |
| 556 | } |
| 557 | |
| 558 | /*! \brief Stops the timer |
| 559 | \returns True if successful |
| 560 | */ |
| 561 | bool WatchDogThread::stopTimer(void) noexcept |
| 562 | { |
| 563 | if (!isAlive()) |
| 564 | return true; |
| 565 | |
| 566 | #ifdef _WIN32 |
| 567 | ::SetEvent(m_stop); |
| 568 | ::SetThreadPriority(m_thread, THREAD_PRIORITY_ABOVE_NORMAL); |
| 569 | |
| 570 | while (isAlive()) |
| 571 | xsYield(); |
| 572 | if (::CloseHandle(m_thread) == 0) |
| 573 | { |
| 574 | DWORD lastErr = GetLastError(); |
| 575 | (void)lastErr; |
| 576 | return false; |
| 577 | } |
| 578 | #else |
| 579 | int rv; |
| 580 | int32_t policy; |
| 581 | struct sched_param param; |
| 582 | |
| 583 | m_stop = true; |
| 584 | rv = pthread_getschedparam(m_thread, &policy, ¶m); |
| 585 | if (rv) |
| 586 | { |
| 587 | switch(errno) |
| 588 | { |
| 589 | case ESRCH: return false; |
| 590 | default: break; |
| 591 | } |
| 592 | } |
| 593 | param.sched_priority = sched_get_priority_max(policy); |
| 594 | |
| 595 | rv = pthread_setschedparam(m_thread, policy, ¶m); |
| 596 | if (rv) |
| 597 | { |
| 598 | switch (errno) |
| 599 | { |
| 600 | case ESRCH: |
| 601 | case EINVAL: |
| 602 | case ENOTSUP: |
| 603 | case EPERM: return false; |
| 604 | default: break; |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | rv = pthread_join(m_thread, NULL); |
| 609 | if (rv) |
| 610 | { |
| 611 | switch(errno) |
| 612 | { |
| 613 | case EINVAL: |
| 614 | case ESRCH: |
| 615 | case EDEADLK: |
| 616 | default: break; |
| 617 | } |
| 618 | } |
| 619 | m_running = false; |
| 620 | m_thread = XSENS_INVALID_THREAD; |
| 621 | #endif |
| 622 | m_thread = XSENS_INVALID_THREAD; |
| 623 | return true; |
| 624 | } |
| 625 | |
| 626 | XSENS_THREAD_RETURN WatchDogThread::threadInit(void* obj) |
| 627 | { |
| 628 | WatchDogThread* thread = reinterpret_cast<WatchDogThread*>(obj); |
| 629 | if (thread->m_name) |
| 630 | xsNameThisThread(thread->m_name); |
| 631 | |
| 632 | thread->threadMain(); |
| 633 | return 0; |
| 634 | } |
| 635 | |
| 636 | void WatchDogThread::threadMain(void) |
| 637 | { |
| 638 | XsTimeStamp toTime((int64_t) (XsTimeStamp::now().msTime() + m_timeout)); |
| 639 | |
| 640 | #ifdef _WIN32 |
| 641 | HANDLE hlist[2]; |
| 642 | #endif |
| 643 | bool go = true; |
| 644 | while (go) |
| 645 | { |
| 646 | #ifdef _WIN32 |
| 647 | uint32_t timeout = (uint32_t) (toTime - XsTimeStamp::now()).msTime(); |
| 648 | if (timeout > m_timeout) |
| 649 | break; |
| 650 | hlist[0] = m_reset; |
| 651 | hlist[1] = m_stop; |
| 652 | |
| 653 | switch(::WaitForMultipleObjects(2,hlist,FALSE,timeout)) |
| 654 | { |
| 655 | case WAIT_OBJECT_0: // m_reset |
| 656 | // received an update for the timer |
| 657 | toTime = XsTimeStamp::now() + XsTimeStamp((int) m_timeout); |
| 658 | ::ResetEvent(m_reset); |
| 659 | continue; |
| 660 | |
| 661 | case WAIT_OBJECT_0+1: // m_stop |
| 662 | case WAIT_ABANDONED: |
| 663 | default: |
| 664 | go = false; |
| 665 | break; |
| 666 | |
| 667 | case WAIT_TIMEOUT: |
| 668 | break; |
| 669 | } |
| 670 | #else |
| 671 | Lock lock(&m_mutex, true); |
| 672 | lock.unlock(); |
| 673 | |
| 674 | uint32_t timeout; |
| 675 | |
| 676 | while (go) |
| 677 | { |
| 678 | timeout = static_cast<uint32_t>((toTime - XsTimeStamp::now()).msTime()); |
| 679 | if (timeout > m_timeout) |
| 680 | break; |
| 681 | |
| 682 | lock.lock(); |
| 683 | if (m_reset) |
| 684 | { |
| 685 | toTime = XsTimeStamp((XsTimeStamp::now().msTime() + m_timeout)); |
| 686 | m_reset = false; |
| 687 | } |
| 688 | lock.unlock(); |
| 689 | |
| 690 | if (m_stop) |
| 691 | go = false; |
| 692 | } |
| 693 | #endif |
| 694 | break; |
| 695 | } |
| 696 | if (go) |
| 697 | m_func(m_param); |
| 698 | } |
| 699 | |
| 700 | /*! \brief Resets the timer and sets a timeout |
| 701 | \param timeout The timeout value to set |
| 702 | \returns True if successful |
| 703 | */ |
| 704 | bool WatchDogThread::resetTimer(uint32_t timeout) |
| 705 | { |
| 706 | if (!isRunning()) |
| 707 | return false; |
| 708 | |
| 709 | #ifdef _WIN32 |
| 710 | if (timeout != 0) |
| 711 | m_timeout = timeout; |
| 712 | ::SetEvent(m_reset); |
| 713 | #else |
| 714 | Lock lock(&m_mutex); |
| 715 | |
| 716 | m_timeout = timeout; |
| 717 | m_reset = true; |
| 718 | #endif |
| 719 | return true; |
| 720 | } |
| 721 | |
| 722 | #ifdef _WIN32 |
| 723 | Semaphore::Semaphore(int32_t initVal, uint32_t nofOtherHandles, HANDLE *otherHandles) |
| 724 | { |
| 725 | m_nofHandles = nofOtherHandles+1; |
| 726 | m_handleList = new HANDLE[m_nofHandles]; |
| 727 | for (uint32_t i=0; i<m_nofHandles-1; i++) |
| 728 | m_handleList[i] = otherHandles[i]; |
| 729 | m_handleList[m_nofHandles-1] = CreateSemaphore(NULL, initVal, 0x7fffffff, NULL); |
| 730 | } |
| 731 | |
| 732 | Semaphore::~Semaphore(void) |
| 733 | { |
| 734 | post(); |
| 735 | CloseHandle(m_handleList[m_nofHandles-1]); |
| 736 | delete[] m_handleList; |
| 737 | } |
| 738 | |
| 739 | bool Semaphore::wait1() |
| 740 | { |
| 741 | return wait1(static_cast<uint32_t>(-1)); |
| 742 | } |
| 743 | |
| 744 | bool Semaphore::wait1(uint32_t timeout) |
| 745 | { |
| 746 | for (;;) // loop + timeout for debugging only |
| 747 | { |
| 748 | DWORD r = WaitForMultipleObjects(m_nofHandles, m_handleList, FALSE, timeout); |
| 749 | if (r == WAIT_TIMEOUT) |
| 750 | return false; |
| 751 | if (r < WAIT_OBJECT_0 + m_nofHandles) |
| 752 | return r-WAIT_OBJECT_0 == m_nofHandles-1; |
| 753 | if (r != WAIT_TIMEOUT) |
| 754 | return false; |
| 755 | xsYield(); // prevent race condition |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | int32_t Semaphore::post(int32_t increment) noexcept |
| 760 | { |
| 761 | LONG prev; |
| 762 | ReleaseSemaphore(m_handleList[m_nofHandles-1], increment, &prev); |
| 763 | return (int32_t) prev; |
| 764 | } |
| 765 | |
| 766 | #else // _WIN32 |
| 767 | |
| 768 | Semaphore::Semaphore(int32_t initVal, uint32_t, sem_t *) : |
| 769 | m_semname(nullptr), |
| 770 | m_handle(SEM_FAILED) |
| 771 | { |
| 772 | #if defined(SEM_VALUE_MAX) && INT32_MAX > SEM_VALUE_MAX |
| 773 | if (initVal > SEM_VALUE_MAX) |
| 774 | initVal = SEM_VALUE_MAX; |
| 775 | #endif |
| 776 | |
| 777 | uint64_t id = (uint64_t)this; |
| 778 | char semname[20]; |
| 779 | |
| 780 | while (true) |
| 781 | { |
| 782 | sprintf(semname, "%" PRINTF_INT64_MODIFIER "x", id); |
| 783 | m_semname = strdup(semname); |
| 784 | m_handle = sem_open(semname, O_EXCL|O_CREAT, S_IRWXU, initVal); |
| 785 | if (m_handle != SEM_FAILED) |
| 786 | break; |
| 787 | |
| 788 | if (errno != EEXIST) |
| 789 | { |
| 790 | perror("opening semaphore"); |
| 791 | exit(-1); |
| 792 | } |
| 793 | |
| 794 | id++; |
| 795 | free(m_semname); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | Semaphore::~Semaphore(void) |
| 800 | { |
| 801 | post(); |
| 802 | sem_unlink(m_semname); |
| 803 | free(m_semname); |
| 804 | } |
| 805 | |
| 806 | bool Semaphore::wait1() |
| 807 | { |
| 808 | return wait1(static_cast<uint32_t>(-1)); |
| 809 | } |
| 810 | |
| 811 | bool Semaphore::wait1(uint32_t ms) |
| 812 | { |
| 813 | if (ms == UINT32_MAX) |
| 814 | return sem_wait(m_handle); |
| 815 | |
| 816 | #if _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 |
| 817 | timespec ts; |
| 818 | |
| 819 | clock_gettime(CLOCK_REALTIME, &ts); |
| 820 | |
| 821 | int64_t s = ms/1000; |
| 822 | ts.tv_sec += s; |
| 823 | |
| 824 | ms -= s*1000; |
| 825 | int64_t ns = ts.tv_nsec + (ms * 1000000); |
| 826 | |
| 827 | ts.tv_sec += ns / 1000000000L; |
| 828 | ts.tv_nsec = ns % 1000000000L; |
| 829 | |
| 830 | return sem_timedwait(m_handle, &ts) == 0; |
| 831 | #else |
| 832 | XsTimeStamp end = XsTimeStamp::now() + XsTimeStamp(int64_t(ms)); |
| 833 | |
| 834 | while (XsTimeStamp::now() < end) |
| 835 | { |
| 836 | if (sem_trywait(m_handle) == 0) |
| 837 | return true; |
| 838 | else |
| 839 | xsYield(); |
| 840 | } |
| 841 | |
| 842 | return false; |
| 843 | #endif |
| 844 | } |
| 845 | |
| 846 | #ifndef __APPLE__ |
| 847 | int32_t Semaphore::post(int32_t increment) throw() |
| 848 | { |
| 849 | int prev; |
| 850 | sem_getvalue(m_handle, &prev); |
| 851 | for (int i = 0; i < increment; i++) |
| 852 | sem_post(m_handle); |
| 853 | return (int32_t)prev; |
| 854 | } |
| 855 | #else |
| 856 | int32_t Semaphore::post(int32_t increment) throw() |
| 857 | { |
| 858 | int prev =0; |
| 859 | for (int i = 0; i < increment; i++) |
| 860 | sem_post(m_handle); |
| 861 | return (int32_t)prev; |
| 862 | } |
| 863 | #endif |
| 864 | #endif // _WIN32 |
| 865 | |
| 866 | #ifdef __APPLE__ |
| 867 | /*! \brief An implementation of linux' clock_gettime() |
| 868 | |
| 869 | clock_gettime() is not available on Apple/Darwin platforms. This function helps |
| 870 | maintaining compatibility with Linux code. |
| 871 | |
| 872 | This comes straight from xstime. We should probably move thread primitives into xstypes. |
| 873 | */ |
| 874 | #ifndef CLOCK_REALTIME |
| 875 | #define CLOCK_REALTIME 0 |
| 876 | #endif |
| 877 | static int clock_gettime(int clk_id, struct timespec *tp) |
| 878 | { |
| 879 | (void)clk_id; |
| 880 | struct timeval now; |
| 881 | |
| 882 | int rv = gettimeofday(&now, NULL); |
| 883 | if (rv != 0) |
| 884 | return rv; |
| 885 | |
| 886 | tp->tv_sec = now.tv_sec; |
| 887 | tp->tv_nsec = now.tv_usec * 1000; |
| 888 | |
| 889 | return 0; |
| 890 | } |
| 891 | #endif |
| 892 | |
| 893 | /*! \brief Create a wait condition */ |
| 894 | WaitCondition::WaitCondition(Mutex &m) : m_mutex(m) |
| 895 | { |
| 896 | #ifdef _WIN32 |
| 897 | InitializeConditionVariable(&m_cond); |
| 898 | #else |
| 899 | pthread_condattr_init(&m_condattr); |
| 900 | #if !defined(__APPLE__) && (defined(_POSIX_CLOCK_SELECTION) || defined(_SC_CLOCK_SELECTION)) && !defined(ANDROID) |
| 901 | m_clockId = CLOCK_MONOTONIC; |
| 902 | if (pthread_condattr_setclock(&m_condattr, m_clockId) != 0) |
| 903 | pthread_condattr_getclock(&m_condattr, &m_clockId); |
| 904 | #else |
| 905 | /* we'll fall back to the wallclock, but we may be influenced by |
| 906 | * time keeping software (ntp, date), which doesn't happen with |
| 907 | * the monotonic clock |
| 908 | */ |
| 909 | m_clockId = CLOCK_REALTIME; |
| 910 | #endif |
| 911 | pthread_cond_init(&m_cond, &m_condattr); |
| 912 | #endif |
| 913 | } |
| 914 | |
| 915 | /*! \brief Destroy the wait condition */ |
| 916 | WaitCondition::~WaitCondition() |
| 917 | { |
| 918 | try |
| 919 | { |
| 920 | broadcast(); |
| 921 | #ifndef _WIN32 |
| 922 | pthread_cond_destroy(&m_cond); |
| 923 | pthread_condattr_destroy(&m_condattr); |
| 924 | #endif |
| 925 | } |
| 926 | catch (...) |
| 927 | { |
| 928 | } |
| 929 | } |
| 930 | |
| 931 | /*! \brief Unblock a single waiting thread */ |
| 932 | void WaitCondition::signal() |
| 933 | { |
| 934 | #ifdef _WIN32 |
| 935 | WakeConditionVariable(&m_cond); |
| 936 | #else |
| 937 | pthread_cond_signal(&m_cond); |
| 938 | #endif |
| 939 | } |
| 940 | |
| 941 | /*! \brief Unblock all waiting threads */ |
| 942 | void WaitCondition::broadcast() |
| 943 | { |
| 944 | #ifdef _WIN32 |
| 945 | WakeAllConditionVariable(&m_cond); |
| 946 | #else |
| 947 | pthread_cond_broadcast(&m_cond); |
| 948 | #endif |
| 949 | } |
| 950 | |
| 951 | /*! \brief Wait until we're signalled to continue |
| 952 | * |
| 953 | * \details Before calling this function, it is required that the mutex |
| 954 | * provided during construction is _locked_. This function unlocks the mutex |
| 955 | * internally, and returns with the mutex locked again. |
| 956 | * |
| 957 | * \return true if we were signalled, false otherwise |
| 958 | */ |
| 959 | bool WaitCondition::wait() |
| 960 | { |
| 961 | #ifdef _WIN32 |
| 962 | return SleepConditionVariableCS(&m_cond, &m_mutex.m_mutex, INFINITE) != 0; |
| 963 | #else |
| 964 | return pthread_cond_wait(&m_cond, &m_mutex.m_mutex) == 0; |
| 965 | #endif |
| 966 | } |
| 967 | |
| 968 | /*! \brief Wait until we're signalled to continue, or until timeout [ms] has passed |
| 969 | * |
| 970 | * \details Before calling this function, it is required that the mutex |
| 971 | * provided during construction is _locked_. This function unlocks the mutex |
| 972 | * internally, and returns with the mutex locked again. |
| 973 | * |
| 974 | * \param timeout The timeout value in ms |
| 975 | * |
| 976 | * \return true if we were signalled, false otherwise |
| 977 | */ |
| 978 | bool WaitCondition::wait(uint32_t timeout) |
| 979 | { |
| 980 | #ifdef _WIN32 |
| 981 | return SleepConditionVariableCS(&m_cond, &m_mutex.m_mutex, timeout) != 0; |
| 982 | #else |
| 983 | static const int64_t NANOS_PER_MILLI = 1000000; |
| 984 | static const int64_t NANOS_PER_ONE = NANOS_PER_MILLI * 1000; |
| 985 | |
| 986 | struct timespec time; |
| 987 | int64_t nsec; |
| 988 | |
| 989 | clock_gettime(m_clockId, &time); |
| 990 | |
| 991 | nsec = time.tv_nsec + timeout * NANOS_PER_MILLI; |
| 992 | time.tv_nsec = nsec % NANOS_PER_ONE; |
| 993 | time.tv_sec += nsec / NANOS_PER_ONE; |
| 994 | |
| 995 | return pthread_cond_timedwait(&m_cond, &m_mutex.m_mutex, &time) == 0; |
| 996 | #endif |
| 997 | } |
| 998 | |
| 999 | #if defined(_WIN32) |
| 1000 | /*! \brief Constructor, initializes the event in the reset state */ |
| 1001 | WaitEvent::WaitEvent() |
| 1002 | : m_waiterCount(0) |
| 1003 | , m_terminating(false) |
| 1004 | { |
| 1005 | m_event = ::CreateEventA(NULL, TRUE, FALSE, NULL); |
| 1006 | } |
| 1007 | |
| 1008 | /*! \brief Destructor, terminates the event and waits for waiting threads to be notified before finishing */ |
| 1009 | WaitEvent::~WaitEvent() |
| 1010 | { |
| 1011 | try |
| 1012 | { |
| 1013 | terminate(); |
| 1014 | } |
| 1015 | catch(...) |
| 1016 | {} |
| 1017 | assert(m_waiterCount == 0); |
| 1018 | ::CloseHandle(m_event); |
| 1019 | m_event = INVALID_HANDLE_VALUE; |
| 1020 | } |
| 1021 | |
| 1022 | /*! \brief Wait for the event to be set or object termination |
| 1023 | \return true if the event is set and the object is not being terminated |
| 1024 | */ |
| 1025 | bool WaitEvent::wait() |
| 1026 | { |
| 1027 | if (m_terminating) |
| 1028 | return false; |
| 1029 | |
| 1030 | ++m_waiterCount; |
| 1031 | |
| 1032 | switch(::WaitForSingleObject(m_event, INFINITE)) |
| 1033 | { |
| 1034 | case WAIT_ABANDONED: |
| 1035 | case WAIT_TIMEOUT: |
| 1036 | --m_waiterCount; |
| 1037 | return false; |
| 1038 | case WAIT_OBJECT_0: |
| 1039 | --m_waiterCount; |
| 1040 | return !m_terminating; |
| 1041 | default: |
| 1042 | --m_waiterCount; |
| 1043 | return false; |
| 1044 | } |
| 1045 | } |
| 1046 | |
| 1047 | /*! \brief Set the event. |
| 1048 | \details Waiting items will (all) be notified and allowed to run |
| 1049 | */ |
| 1050 | void WaitEvent::set() |
| 1051 | { |
| 1052 | ::SetEvent(m_event); |
| 1053 | } |
| 1054 | |
| 1055 | /*! \brief Reset the event. |
| 1056 | \details Any wait() call will block until set() or terminate() is called. |
| 1057 | \note After terminate() has been called, reset() will not reset the event anymore |
| 1058 | */ |
| 1059 | void WaitEvent::reset() |
| 1060 | { |
| 1061 | if (!m_terminating) |
| 1062 | ::ResetEvent(m_event); |
| 1063 | } |
| 1064 | #else |
| 1065 | WaitEvent::WaitEvent() |
| 1066 | : m_waiterCount(0) |
| 1067 | , m_terminating(false) |
| 1068 | { |
| 1069 | pthread_mutex_init(&m_mutex, 0); |
| 1070 | pthread_cond_init(&m_cond, 0); |
| 1071 | m_triggered = false; |
| 1072 | } |
| 1073 | |
| 1074 | WaitEvent::~WaitEvent() |
| 1075 | { |
| 1076 | terminate(); |
| 1077 | pthread_cond_destroy(&m_cond); |
| 1078 | pthread_mutex_destroy(&m_mutex); |
| 1079 | } |
| 1080 | |
| 1081 | /*! \brief Wait for the event to be set or object termination |
| 1082 | \return true if the event is set and the object is not being terminated |
| 1083 | */ |
| 1084 | bool WaitEvent::wait() |
| 1085 | { |
| 1086 | if (m_terminating) |
| 1087 | return false; |
| 1088 | |
| 1089 | ++m_waiterCount; |
| 1090 | pthread_mutex_lock(&m_mutex); |
| 1091 | while (!m_triggered && !m_terminating) |
| 1092 | pthread_cond_wait(&m_cond, &m_mutex); |
| 1093 | pthread_mutex_unlock(&m_mutex); |
| 1094 | --m_waiterCount; |
| 1095 | return !m_terminating; |
| 1096 | } |
| 1097 | |
| 1098 | /*! \brief Set the event. |
| 1099 | \details Waiting items will (all) be notified and allowed to run |
| 1100 | */ |
| 1101 | void WaitEvent::set() |
| 1102 | { |
| 1103 | pthread_mutex_lock(&m_mutex); |
| 1104 | m_triggered = true; |
| 1105 | pthread_cond_signal(&m_cond); |
| 1106 | pthread_mutex_unlock(&m_mutex); |
| 1107 | } |
| 1108 | |
| 1109 | /*! \brief Reset the event. |
| 1110 | \details Any wait() call will block until set() or terminate() is called. |
| 1111 | \note After terminate() has been called, reset() will not reset the event anymore |
| 1112 | */ |
| 1113 | void WaitEvent::reset() |
| 1114 | { |
| 1115 | if (!m_terminating) |
| 1116 | { |
| 1117 | pthread_mutex_lock(&m_mutex); |
| 1118 | m_triggered = false; |
| 1119 | pthread_mutex_unlock(&m_mutex); |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | #endif |
| 1124 | |
| 1125 | /*! \brief Terminates the thread |
| 1126 | */ |
| 1127 | void WaitEvent::terminate() |
| 1128 | { |
| 1129 | m_terminating = true; |
| 1130 | set(); |
| 1131 | |
| 1132 | while (m_waiterCount > 0) |
| 1133 | XsTime_msleep(2); |
| 1134 | } |
| 1135 | |
| 1136 | } // namespace xsens |