c - pthread time-out or cancel, using pthread_cond_timedwait, or what? -


i have thread waits (blocking) on message queue messages process. polling not option.

when start message arrives, set variable must either reset after given time delay, or reset arrival of stop message. if set, repeated start should extend set-time given time period (could re-start).

in meantime, thread should carry on processing other messages arrive.

to mind, way spawn , detach new pthread handle time-out. thread either time-out , send stop message parent before exiting, or killed/cancelled prematurely if stop message received parent thread.

i've been reading pthreads documentation , it's not entirely clear me best way of doing this:

  1. i create thread sleeps given time , sends stop message, , pthread_cancel() if stop message arrives sooner. seems implied in docs (but not explicitly stated) that, in case, "cancel" action kill thread mid-sleep, no further actions.

  2. i create thread uses pthread_cond_timedwait() wait on condition, per this example. looks "proper" cumbersome.

  3. something similar 1 fork()ing process watches flag variable , either times out or gives if flag reset.

  4. use sigalarm handler, plus alarm() set / unset timed signal (sounds simple, practice seems bit untidy , can have 1 alarm)

delays in seconds range, accuracy ~0.1sec nice. i'm not keen on way pthread_cond_timedwait uses absolute time, there's chance user may set clock , throw things out of kilter (not end of world, seems non-optimal me).

it's not clear me examples around net either "pthread_cancel" or "pthread_cond_timedwait" work / work cleanly detached thread?

i won't post code of current favoured option pretty copy-paste of example in option 2.

i don't see agonizing over. best understand description, timers plainly way go.

  • create timer timer_create deliver signal if time elapses. if doing setting switch on variable done in signal handler itself
  • if stop message while there time remaining, disarm timer timer_settime
  • if 2nd start msg while timer armed time remaining on timer timer_gettime, add new amount of time it, , reset timer timer_settime.
  • delete timer when done with timer_delete

unlike alarm or itimer interval timers not limited single timer.

as aside, if using posix message queues , messages few , far between may worth using mq_notify. instead of blocking on mq_receive day can set spin thread whenever new message put in empty queue , process , messages until queue again empty , thread ends.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -