README.CV
上传用户:zhenyu
上传日期:2022-04-24
资源大小:268k
文件大小:88k
源码类别:

视频捕捉/采集

开发平台:

Visual C++

  1. README.CV -- Condition Variables
  2. --------------------------------
  3. The original implementation of condition variables in
  4. pthreads-win32 was based on a discussion paper:
  5. "Strategies for Implementing POSIX Condition Variables
  6. on Win32": http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  7. The changes suggested below were made on Feb 6 2001. This
  8. file is included in the package for the benefit of anyone
  9. interested in understanding the pthreads-win32 implementation
  10. of condition variables and the (sometimes subtle) issues that
  11. it attempts to resolve.
  12. Thanks go to the individuals whose names appear throughout
  13. the following text.
  14. Ross Johnson
  15. --------------------------------------------------------------------
  16. fyi.. (more detailed problem description/demos + possible fix/patch)
  17. regards,
  18. alexander.
  19. Alexander Terekhov
  20. 31.01.2001 17:43
  21. To:   ace-bugs@cs.wustl.edu
  22. cc:
  23. From: Alexander Terekhov/Germany/IBM@IBMDE
  24. Subject:  Implementation of POSIX CVs: spur.wakeups/lost
  25.       signals/deadlocks/unfairness
  26.     ACE VERSION:
  27.         5.1.12 (pthread-win32 snapshot 2000-12-29)
  28.     HOST MACHINE and OPERATING SYSTEM:
  29.         IBM IntelliStation Z Pro, 2 x XEON 1GHz, Win2K
  30.     TARGET MACHINE and OPERATING SYSTEM, if different from HOST:
  31.     COMPILER NAME AND VERSION (AND PATCHLEVEL):
  32.         Microsoft Visual C++ 6.0
  33.     AREA/CLASS/EXAMPLE AFFECTED:
  34.         Implementation of POSIX condition variables - OS.cpp/.h
  35.     DOES THE PROBLEM AFFECT:
  36.         EXECUTION? YES!
  37.     SYNOPSIS:
  38.         a) spurious wakeups (minor problem)
  39.         b) lost signals
  40.         c) broadcast deadlock
  41.         d) unfairness (minor problem)
  42.     DESCRIPTION:
  43.         Please see attached copy of discussion thread
  44.         from comp.programming.threads for more details on
  45.         some reported problems. (i've also posted a "fyi"
  46.         message to ace-users a week or two ago but
  47.         unfortunately did not get any response so far).
  48.         It seems that current implementation suffers from
  49.         two essential problems:
  50.         1) cond.waiters_count does not accurately reflect
  51.            number of waiters blocked on semaphore - w/o
  52.            proper synchronisation that could result (in the
  53.            time window when counter is not accurate)
  54.            in spurious wakeups organised by subsequent
  55.            _signals  and _broadcasts.
  56.         2) Always having (with no e.g. copy_and_clear/..)
  57.            the same queue in use (semaphore+counter)
  58.            neither signal nor broadcast provide 'atomic'
  59.            behaviour with respect to other threads/subsequent
  60.            calls to signal/broadcast/wait.
  61.         Each problem and combination of both could produce
  62.         various nasty things:
  63.         a) spurious wakeups (minor problem)
  64.              it is possible that waiter(s) which was already
  65.              unblocked even so is still counted as blocked
  66.              waiter. signal and broadcast will release
  67.              semaphore which will produce a spurious wakeup
  68.              for a 'real' waiter coming later.
  69.         b) lost signals
  70.              signalling thread ends up consuming its own
  71.              signal. please see demo/discussion below.
  72.         c) broadcast deadlock
  73.              last_waiter processing code does not correctly
  74.              handle the case with multiple threads
  75.              waiting for the end of broadcast.
  76.              please see demo/discussion below.
  77.         d) unfairness (minor problem)
  78.              without SignalObjectAndWait some waiter(s)
  79.              may end up consuming broadcasted signals
  80.              multiple times (spurious wakeups) because waiter
  81.              thread(s) can be preempted before they call
  82.              semaphore wait (but after count++ and mtx.unlock).
  83.     REPEAT BY:
  84.         See below... run problem demos programs (tennis.cpp and
  85.         tennisb.cpp) number of times concurrently (on multiprocessor)
  86.         and in multiple sessions or just add a couple of "Sleep"s
  87.         as described in the attached copy of discussion thread
  88.         from comp.programming.threads
  89.     SAMPLE FIX/WORKAROUND:
  90.         See attached patch to pthread-win32.. well, I can not
  91.         claim that it is completely bug free but at least my
  92.         test and tests provided by pthreads-win32 seem to work.
  93.         Perhaps that will help.
  94.         regards,
  95.         alexander.
  96. >> Forum: comp.programming.threads
  97. >> Thread: pthread_cond_* implementation questions
  98. .
  99. .
  100. .
  101. David Schwartz <davids@webmaster.com> wrote:
  102. > terekhov@my-deja.com wrote:
  103. >
  104. >> BTW, could you please also share your view on other perceived
  105. >> "problems" such as nested broadcast deadlock, spurious wakeups
  106. >> and (the latest one) lost signals??
  107. >
  108. >I'm not sure what you mean. The standard allows an implementation
  109. >to do almost whatever it likes. In fact, you could implement
  110. >pthread_cond_wait by releasing the mutex, sleeping a random
  111. >amount of time, and then reacquiring the mutex. Of course,
  112. >this would be a pretty poor implementation, but any code that
  113. >didn't work under that implementation wouldn't be strictly
  114. >compliant.
  115. The implementation you suggested is indeed correct
  116. one (yes, now I see it :). However it requires from
  117. signal/broadcast nothing more than to "{ return 0; }"
  118. That is not the case for pthread-win32 and ACE
  119. implementations. I do think that these implementations
  120. (basically the same implementation) have some serious
  121. problems with wait/signal/broadcast calls. I am looking
  122. for help to clarify whether these problems are real
  123. or not. I think that I can demonstrate what I mean
  124. using one or two small sample programs.
  125. .
  126. .
  127. .
  128. ==========
  129. tennis.cpp
  130. ==========
  131. #include "ace/Synch.h"
  132. #include "ace/Thread.h"
  133. enum GAME_STATE {
  134.   START_GAME,
  135.   PLAYER_A,     // Player A playes the ball
  136.   PLAYER_B,     // Player B playes the ball
  137.   GAME_OVER,
  138.   ONE_PLAYER_GONE,
  139.   BOTH_PLAYERS_GONE
  140. };
  141. enum GAME_STATE             eGameState;
  142. ACE_Mutex*                  pmtxGameStateLock;
  143. ACE_Condition< ACE_Mutex >* pcndGameStateChange;
  144. void*
  145.   playerA(
  146.     void* pParm
  147.   )
  148. {
  149.   // For access to game state variable
  150.   pmtxGameStateLock->acquire();
  151.   // Play loop
  152.   while ( eGameState < GAME_OVER ) {
  153.     // Play the ball
  154.     cout << endl << "PLAYER-A" << endl;
  155.     // Now its PLAYER-B's turn
  156.     eGameState = PLAYER_B;
  157.     // Signal to PLAYER-B that now it is his turn
  158.     pcndGameStateChange->signal();
  159.     // Wait until PLAYER-B finishes playing the ball
  160.     do {
  161.       pcndGameStateChange->wait();
  162.       if ( PLAYER_B == eGameState )
  163.         cout << endl << "----PLAYER-A: SPURIOUS WAKEUP!!!" << endl;
  164.     } while ( PLAYER_B == eGameState );
  165.   }
  166.   // PLAYER-A gone
  167.   eGameState = (GAME_STATE)(eGameState+1);
  168.   cout << endl << "PLAYER-A GONE" << endl;
  169.   // No more access to state variable needed
  170.   pmtxGameStateLock->release();
  171.   // Signal PLAYER-A gone event
  172.   pcndGameStateChange->broadcast();
  173.   return 0;
  174. }
  175. void*
  176.   playerB(
  177.     void* pParm
  178.   )
  179. {
  180.   // For access to game state variable
  181.   pmtxGameStateLock->acquire();
  182.   // Play loop
  183.   while ( eGameState < GAME_OVER ) {
  184.     // Play the ball
  185.     cout << endl << "PLAYER-B" << endl;
  186.     // Now its PLAYER-A's turn
  187.     eGameState = PLAYER_A;
  188.     // Signal to PLAYER-A that now it is his turn
  189.     pcndGameStateChange->signal();
  190.     // Wait until PLAYER-A finishes playing the ball
  191.     do {
  192.       pcndGameStateChange->wait();
  193.       if ( PLAYER_A == eGameState )
  194.         cout << endl << "----PLAYER-B: SPURIOUS WAKEUP!!!" << endl;
  195.     } while ( PLAYER_A == eGameState );
  196.   }
  197.   // PLAYER-B gone
  198.   eGameState = (GAME_STATE)(eGameState+1);
  199.   cout << endl << "PLAYER-B GONE" << endl;
  200.   // No more access to state variable needed
  201.   pmtxGameStateLock->release();
  202.   // Signal PLAYER-B gone event
  203.   pcndGameStateChange->broadcast();
  204.   return 0;
  205. }
  206. int
  207. main (int, ACE_TCHAR *[])
  208. {
  209.   pmtxGameStateLock   = new ACE_Mutex();
  210.   pcndGameStateChange = new ACE_Condition< ACE_Mutex >( *pmtxGameStateLock
  211. );
  212.   // Set initial state
  213.   eGameState = START_GAME;
  214.   // Create players
  215.   ACE_Thread::spawn( playerA );
  216.   ACE_Thread::spawn( playerB );
  217.   // Give them 5 sec. to play
  218.   Sleep( 5000 );//sleep( 5 );
  219.   // Set game over state
  220.   pmtxGameStateLock->acquire();
  221.   eGameState = GAME_OVER;
  222.   // Let them know
  223.   pcndGameStateChange->broadcast();
  224.   // Wait for players to stop
  225.   do {
  226.     pcndGameStateChange->wait();
  227.   } while ( eGameState < BOTH_PLAYERS_GONE );
  228.   // Cleanup
  229.   cout << endl << "GAME OVER" << endl;
  230.   pmtxGameStateLock->release();
  231.   delete pcndGameStateChange;
  232.   delete pmtxGameStateLock;
  233.   return 0;
  234. }
  235. ===========
  236. tennisb.cpp
  237. ===========
  238. #include "ace/Synch.h"
  239. #include "ace/Thread.h"
  240. enum GAME_STATE {
  241.   START_GAME,
  242.   PLAYER_A,     // Player A playes the ball
  243.   PLAYER_B,     // Player B playes the ball
  244.   GAME_OVER,
  245.   ONE_PLAYER_GONE,
  246.   BOTH_PLAYERS_GONE
  247. };
  248. enum GAME_STATE             eGameState;
  249. ACE_Mutex*                  pmtxGameStateLock;
  250. ACE_Condition< ACE_Mutex >* pcndGameStateChange;
  251. void*
  252.   playerA(
  253.     void* pParm
  254.   )
  255. {
  256.   // For access to game state variable
  257.   pmtxGameStateLock->acquire();
  258.   // Play loop
  259.   while ( eGameState < GAME_OVER ) {
  260.     // Play the ball
  261.     cout << endl << "PLAYER-A" << endl;
  262.     // Now its PLAYER-B's turn
  263.     eGameState = PLAYER_B;
  264.     // Signal to PLAYER-B that now it is his turn
  265.     pcndGameStateChange->broadcast();
  266.     // Wait until PLAYER-B finishes playing the ball
  267.     do {
  268.       pcndGameStateChange->wait();
  269.       if ( PLAYER_B == eGameState )
  270.         cout << endl << "----PLAYER-A: SPURIOUS WAKEUP!!!" << endl;
  271.     } while ( PLAYER_B == eGameState );
  272.   }
  273.   // PLAYER-A gone
  274.   eGameState = (GAME_STATE)(eGameState+1);
  275.   cout << endl << "PLAYER-A GONE" << endl;
  276.   // No more access to state variable needed
  277.   pmtxGameStateLock->release();
  278.   // Signal PLAYER-A gone event
  279.   pcndGameStateChange->broadcast();
  280.   return 0;
  281. }
  282. void*
  283.   playerB(
  284.     void* pParm
  285.   )
  286. {
  287.   // For access to game state variable
  288.   pmtxGameStateLock->acquire();
  289.   // Play loop
  290.   while ( eGameState < GAME_OVER ) {
  291.     // Play the ball
  292.     cout << endl << "PLAYER-B" << endl;
  293.     // Now its PLAYER-A's turn
  294.     eGameState = PLAYER_A;
  295.     // Signal to PLAYER-A that now it is his turn
  296.     pcndGameStateChange->broadcast();
  297.     // Wait until PLAYER-A finishes playing the ball
  298.     do {
  299.       pcndGameStateChange->wait();
  300.       if ( PLAYER_A == eGameState )
  301.         cout << endl << "----PLAYER-B: SPURIOUS WAKEUP!!!" << endl;
  302.     } while ( PLAYER_A == eGameState );
  303.   }
  304.   // PLAYER-B gone
  305.   eGameState = (GAME_STATE)(eGameState+1);
  306.   cout << endl << "PLAYER-B GONE" << endl;
  307.   // No more access to state variable needed
  308.   pmtxGameStateLock->release();
  309.   // Signal PLAYER-B gone event
  310.   pcndGameStateChange->broadcast();
  311.   return 0;
  312. }
  313. int
  314. main (int, ACE_TCHAR *[])
  315. {
  316.   pmtxGameStateLock   = new ACE_Mutex();
  317.   pcndGameStateChange = new ACE_Condition< ACE_Mutex >( *pmtxGameStateLock
  318. );
  319.   // Set initial state
  320.   eGameState = START_GAME;
  321.   // Create players
  322.   ACE_Thread::spawn( playerA );
  323.   ACE_Thread::spawn( playerB );
  324.   // Give them 5 sec. to play
  325.   Sleep( 5000 );//sleep( 5 );
  326.   // Make some noise
  327.   pmtxGameStateLock->acquire();
  328.   cout << endl << "---Noise ON..." << endl;
  329.   pmtxGameStateLock->release();
  330.   for ( int i = 0; i < 100000; i++ )
  331.     pcndGameStateChange->broadcast();
  332.   cout << endl << "---Noise OFF" << endl;
  333.   // Set game over state
  334.   pmtxGameStateLock->acquire();
  335.   eGameState = GAME_OVER;
  336.   cout << endl << "---Stopping the game..." << endl;
  337.   // Let them know
  338.   pcndGameStateChange->broadcast();
  339.   // Wait for players to stop
  340.   do {
  341.     pcndGameStateChange->wait();
  342.   } while ( eGameState < BOTH_PLAYERS_GONE );
  343.   // Cleanup
  344.   cout << endl << "GAME OVER" << endl;
  345.   pmtxGameStateLock->release();
  346.   delete pcndGameStateChange;
  347.   delete pmtxGameStateLock;
  348.   return 0;
  349. }
  350. .
  351. .
  352. .
  353. David Schwartz <davids@webmaster.com> wrote:
  354. >> > It's compliant
  355. >>
  356. >> That is really good.
  357. >
  358. >> Tomorrow (I have to go urgently now) I will try to
  359. >> demonstrate the lost-signal "problem" of current
  360. >> pthread-win32 and ACE-(variant w/o SingleObjectAndWait)
  361. >> implementations: players start suddenly drop their balls :-)
  362. >> (with no change in source code).
  363. >
  364. >Signals aren't lost, they're going to the main thread,
  365. >which isn't coded correctly to handle them. Try this:
  366. >
  367. >  // Wait for players to stop
  368. >  do {
  369. >
  370. >    pthread_cond_wait( &cndGameStateChange,&mtxGameStateLock );
  371. >printf("Main thread stole a signaln");
  372. >
  373. >  } while ( eGameState < BOTH_PLAYERS_GONE );
  374. >
  375. >I bet everytime you thing a signal is lost, you'll see that printf.
  376. >The signal isn't lost, it was stolen by another thread.
  377. well, you can probably loose your bet.. it was indeed stolen
  378. by "another" thread but not the one you seem to think of.
  379. I think that what actually happens is the following:
  380. H:SAUXXptPTHREADSTESTS>tennis3.exe
  381. PLAYER-A
  382. PLAYER-B
  383. ----PLAYER-B: SPURIOUS WAKEUP!!!
  384. PLAYER-A GONE
  385. PLAYER-B GONE
  386. GAME OVER
  387. H:SAUXXptPTHREADSTESTS>
  388. here you can see that PLAYER-B after playing his first
  389. ball (which came via signal from PLAYER-A) just dropped
  390. it down. What happened is that his signal to player A
  391. was consumed as spurious wakeup by himself (player B).
  392. The implementation has a problem:
  393. ================
  394. waiting threads:
  395. ================
  396. { /** Critical Section
  397.   inc cond.waiters_count
  398. }
  399.   /*
  400.   /* Atomic only if using Win32 SignalObjectAndWait
  401.   /*
  402.   cond.mtx.release
  403.   /*** ^^-- A THREAD WHICH DID SIGNAL MAY ACQUIRE THE MUTEX,
  404.   /***      GO INTO WAIT ON THE SAME CONDITION AND OVERTAKE
  405.   /***      ORIGINAL WAITER(S) CONSUMING ITS OWN SIGNAL!
  406.   cond.sem.wait
  407. Player-A after playing game's initial ball went into
  408. wait (called _wait) but was pre-empted before reaching
  409. wait semaphore. He was counted as waiter but was not
  410. actually waiting/blocked yet.
  411. ===============
  412. signal threads:
  413. ===============
  414. { /** Critical Section
  415.   waiters_count = cond.waiters_count
  416. }
  417.   if ( waiters_count != 0 )
  418.     sem.post 1
  419.   endif
  420. Player-B after he received signal/ball from Player A
  421. called _signal. The _signal did see that there was
  422. one waiter blocked on the condition (Player-A) and
  423. released the semaphore.. (but it did not unblock
  424. Player-A because he was not actually blocked).
  425. Player-B thread continued its execution, called _wait,
  426. was counted as second waiter BUT was allowed to slip
  427. through opened semaphore gate (which was opened for
  428. Player-B) and received his own signal. Player B remained
  429. blocked followed by Player A. Deadlock happened which
  430. lasted until main thread came in and said game over.
  431. It seems to me that the implementation fails to
  432. correctly implement the following statement
  433. from specification:
  434. http://www.opengroup.org/
  435. onlinepubs/007908799/xsh/pthread_cond_wait.html
  436. "These functions atomically release mutex and cause
  437. the calling thread to block on the condition variable
  438. cond; atomically here means "atomically with respect
  439. to access by another thread to the mutex and then the
  440. condition variable". That is, if another thread is
  441. able to acquire the mutex after the about-to-block
  442. thread has released it, then a subsequent call to
  443. pthread_cond_signal() or pthread_cond_broadcast()
  444. in that thread behaves as if it were issued after
  445. the about-to-block thread has blocked."
  446. Question: Am I right?
  447. (I produced the program output above by simply
  448. adding ?Sleep( 1 )?:
  449. ================
  450. waiting threads:
  451. ================
  452. { /** Critical Section
  453.   inc cond.waiters_count
  454. }
  455.   /*
  456.   /* Atomic only if using Win32 SignalObjectAndWait
  457.   /*
  458.   cond.mtx.release
  459. Sleep( 1 ); // Win32
  460.   /*** ^^-- A THREAD WHICH DID SIGNAL MAY ACQUIRE THE MUTEX,
  461.   /***      GO INTO WAIT ON THE SAME CONDITION AND OVERTAKE
  462.   /***      ORIGINAL WAITER(S) CONSUMING ITS OWN SIGNAL!
  463.   cond.sem.wait
  464. to the source code of pthread-win32 implementation:
  465. http://sources.redhat.com/cgi-bin/cvsweb.cgi/pthreads/
  466. condvar.c?rev=1.36&content-type=text/
  467. x-cvsweb-markup&cvsroot=pthreads-win32
  468.   /*
  469.   * We keep the lock held just long enough to increment the count of
  470.   * waiters by one (above).
  471.   * Note that we can't keep it held across the
  472.   * call to sem_wait since that will deadlock other calls
  473.   * to pthread_cond_signal
  474.   */
  475.   cleanup_args.mutexPtr = mutex;
  476.   cleanup_args.cv = cv;
  477.   cleanup_args.resultPtr = &result;
  478.   pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *)
  479. &cleanup_args);
  480.   if ((result = pthread_mutex_unlock (mutex)) == 0)
  481.     {((result
  482. Sleep( 1 ); // @AT
  483.       /*
  484.       * Wait to be awakened by
  485.       *              pthread_cond_signal, or
  486.       *              pthread_cond_broadcast, or
  487.       *              a timeout
  488.       *
  489.       * Note:
  490.       *      ptw32_sem_timedwait is a cancelation point,
  491.       *      hence providing the
  492.       *      mechanism for making pthread_cond_wait a cancelation
  493.       *      point. We use the cleanup mechanism to ensure we
  494.       *      re-lock the mutex and decrement the waiters count
  495.       *      if we are canceled.
  496.       */
  497.       if (ptw32_sem_timedwait (&(cv->sema), abstime) == -1)         {
  498.           result = errno;
  499.         }
  500.     }
  501.   pthread_cleanup_pop (1);  /* Always cleanup */
  502. BTW, on my system (2 CPUs) I can manage to get
  503. signals lost even without any source code modification
  504. if I run the tennis program many times in different
  505. shell sessions.
  506. .
  507. .
  508. .
  509. David Schwartz <davids@webmaster.com> wrote:
  510. >terekhov@my-deja.com wrote:
  511. >
  512. >> well, it might be that the program is in fact buggy.
  513. >> but you did not show me any bug.
  514. >
  515. >You're right. I was close but not dead on. I was correct, however,
  516. >that the code is buggy because it uses 'pthread_cond_signal' even
  517. >though not any thread waiting on the condition variable can do the
  518. >job. I was wrong in which thread could be waiting on the cv but
  519. >unable to do the job.
  520. Okay, lets change 'pthread_cond_signal' to 'pthread_cond_broadcast'
  521. but also add some noise from main() right before declaring the game
  522. to be over (I need it in order to demonstrate another problem of
  523. pthread-win32/ACE implementations - broadcast deadlock)...
  524. .
  525. .
  526. .
  527. It is my understanding of POSIX conditions,
  528. that on correct implementation added noise
  529. in form of unnecessary broadcasts from main,
  530. should not break the tennis program. The
  531. only 'side effect' of added noise on correct
  532. implementation would be 'spurious wakeups' of
  533. players (in fact they are not spurious,
  534. players just see them as spurious) unblocked,
  535. not by another player but by main before
  536. another player had a chance to acquire the
  537. mutex and change the game state variable:
  538. .
  539. .
  540. .
  541. PLAYER-B
  542. PLAYER-A
  543. ---Noise ON...
  544. PLAYER-B
  545. PLAYER-A
  546. .
  547. .
  548. .
  549. PLAYER-B
  550. PLAYER-A
  551. ----PLAYER-A: SPURIOUS WAKEUP!!!
  552. PLAYER-B
  553. PLAYER-A
  554. ---Noise OFF
  555. PLAYER-B
  556. ---Stopping the game...
  557. PLAYER-A GONE
  558. PLAYER-B GONE
  559. GAME OVER
  560. H:SAUXXptPTHREADSTESTS>
  561. On pthread-win32/ACE implementations the
  562. program could stall:
  563. .
  564. .
  565. .
  566. PLAYER-A
  567. PLAYER-B
  568. PLAYER-A
  569. PLAYER-B
  570. PLAYER-A
  571. PLAYER-B
  572. PLAYER-A
  573. PLAYER-B
  574. ---Noise ON...
  575. PLAYER-A
  576. ---Noise OFF
  577. ^C
  578. H:SAUXXptPTHREADSTESTS>
  579. The implementation has problems:
  580. ================
  581. waiting threads:
  582. ================
  583. { /** Critical Section
  584.   inc cond.waiters_count
  585. }
  586.   /*
  587.   /* Atomic only if using Win32 SignalObjectAndWait
  588.   /*
  589.   cond.mtx.release
  590.   cond.sem.wait
  591.   /*** ^^-- WAITER CAN BE PREEMPTED AFTER BEING UNBLOCKED...
  592. { /** Critical Section
  593.   dec cond.waiters_count
  594.   /*** ^^- ...AND BEFORE DECREMENTING THE COUNT (1)
  595.   last_waiter = ( cond.was_broadcast &&
  596.                     cond.waiters_count == 0 )
  597.   if ( last_waiter )
  598.     cond.was_broadcast = FALSE
  599.   endif
  600. }
  601.   if ( last_waiter )
  602.     /*
  603.     /* Atomic only if using Win32 SignalObjectAndWait
  604.     /*
  605.     cond.auto_reset_event_or_sem.post /* Event for Win32
  606.     cond.mtx.acquire
  607.   /*** ^^-- ...AND BEFORE CALL TO mtx.acquire (2)
  608.   /*** ^^-- NESTED BROADCASTS RESULT IN A DEADLOCK
  609.   else
  610.     cond.mtx.acquire
  611.   /*** ^^-- ...AND BEFORE CALL TO mtx.acquire (3)
  612.   endif
  613. ==================
  614. broadcast threads:
  615. ==================
  616. { /** Critical Section
  617.   waiters_count = cond.waiters_count
  618.   if ( waiters_count != 0 )
  619.     cond.was_broadcast = TRUE
  620.   endif
  621. }
  622. if ( waiters_count != 0 )
  623.   cond.sem.post waiters_count
  624.   /*** ^^^^^--- SPURIOUS WAKEUPS DUE TO (1)
  625.   cond.auto_reset_event_or_sem.wait /* Event for Win32
  626.   /*** ^^^^^--- DEADLOCK FOR FURTHER BROADCASTS IF THEY
  627.                 HAPPEN TO GO INTO WAIT WHILE PREVIOUS
  628.                 BROADCAST IS STILL IN PROGRESS/WAITING
  629. endif
  630. a) cond.waiters_count does not accurately reflect
  631. number of waiters blocked on semaphore - that could
  632. result (in the time window when counter is not accurate)
  633. in spurios wakeups organised by subsequent _signals
  634. and _broadcasts. From standard compliance point of view
  635. that is OK but that could be a real problem from
  636. performance/efficiency point of view.
  637. b) If subsequent broadcast happen to go into wait on
  638. cond.auto_reset_event_or_sem before previous
  639. broadcast was unblocked from cond.auto_reset_event_or_sem
  640. by its last waiter, one of two blocked threads will
  641. remain blocked because last_waiter processing code
  642. fails to unblock both threads.
  643. In the situation with tennisb.c the Player-B was put
  644. in a deadlock by noise (broadcast) coming from main
  645. thread. And since Player-B holds the game state
  646. mutex when it calls broadcast, the whole program
  647. stalled: Player-A was deadlocked on mutex and
  648. main thread after finishing with producing the noise
  649. was deadlocked on mutex too (needed to declare the
  650. game over)
  651. (I produced the program output above by simply
  652. adding ?Sleep( 1 )?:
  653. ==================
  654. broadcast threads:
  655. ==================
  656. { /** Critical Section
  657.   waiters_count = cond.waiters_count
  658.   if ( waiters_count != 0 )
  659.     cond.was_broadcast = TRUE
  660.   endif
  661. }
  662. if ( waiters_count != 0 )
  663. Sleep( 1 ); //Win32
  664.   cond.sem.post waiters_count
  665.   /*** ^^^^^--- SPURIOUS WAKEUPS DUE TO (1)
  666.   cond.auto_reset_event_or_sem.wait /* Event for Win32
  667.   /*** ^^^^^--- DEADLOCK FOR FURTHER BROADCASTS IF THEY
  668.                 HAPPEN TO GO INTO WAIT WHILE PREVIOUS
  669.                 BROADCAST IS STILL IN PROGRESS/WAITING
  670. endif
  671. to the source code of pthread-win32 implementation:
  672. http://sources.redhat.com/cgi-bin/cvsweb.cgi/pthreads/
  673. condvar.c?rev=1.36&content-type=text/
  674. x-cvsweb-markup&cvsroot=pthreads-win32
  675.   if (wereWaiters)
  676.     {(wereWaiters)sroot=pthreads-win32eb.cgi/pthreads/Yem...m
  677.       /*
  678.       * Wake up all waiters
  679.       */
  680. Sleep( 1 ); //@AT
  681. #ifdef NEED_SEM
  682.       result = (ptw32_increase_semaphore( &cv->sema, cv->waiters )
  683.                  ? 0
  684.                 : EINVAL);
  685. #else /* NEED_SEM */
  686.       result = (ReleaseSemaphore( cv->sema, cv->waiters, NULL )
  687.                  ? 0
  688.                 : EINVAL);
  689. #endif /* NEED_SEM */
  690.     }
  691.   (void) pthread_mutex_unlock(&(cv->waitersLock));
  692.   if (wereWaiters && result == 0)
  693.     {(wereWaiters
  694.       /*
  695.        * Wait for all the awakened threads to acquire their part of
  696.        * the counting semaphore
  697.        */
  698.       if (WaitForSingleObject (cv->waitersDone, INFINITE)
  699.           == WAIT_OBJECT_0)
  700.         {
  701.           result = 0;
  702.         }
  703.       else
  704.         {
  705.           result = EINVAL;
  706.         }
  707.     }
  708.   return (result);
  709. }
  710. BTW, on my system (2 CPUs) I can manage to get
  711. the program stalled even without any source code
  712. modification if I run the tennisb program many
  713. times in different shell sessions.
  714. ===================
  715. pthread-win32 patch
  716. ===================
  717. struct pthread_cond_t_ {
  718.   long            nWaitersBlocked;   /* Number of threads blocked
  719. */
  720.   long            nWaitersUnblocked; /* Number of threads unblocked
  721. */
  722.   long            nWaitersToUnblock; /* Number of threads to unblock
  723. */
  724.   sem_t           semBlockQueue;     /* Queue up threads waiting for the
  725. */
  726.                                      /*   condition to become signalled
  727. */
  728.   sem_t           semBlockLock;      /* Semaphore that guards access to
  729. */
  730.                                      /* | waiters blocked count/block queue
  731. */
  732.                                      /* +-> Mandatory Sync.LEVEL-1
  733. */
  734.   pthread_mutex_t mtxUnblockLock;    /* Mutex that guards access to
  735. */
  736.                                      /* | waiters (to)unblock(ed) counts
  737. */
  738.                                      /* +-> Optional* Sync.LEVEL-2
  739. */
  740. };                                   /* Opt*) for _timedwait and
  741. cancellation*/
  742. int
  743. pthread_cond_init (pthread_cond_t * cond, const pthread_condattr_t * attr)
  744.   int result = EAGAIN;
  745.   pthread_cond_t cv = NULL;
  746.   if (cond == NULL)
  747.     {(cond
  748.       return EINVAL;
  749.     }
  750.   if ((attr != NULL && *attr != NULL) &&
  751.       ((*attr)->pshared == PTHREAD_PROCESS_SHARED))
  752.     {
  753.       /*
  754.        * Creating condition variable that can be shared between
  755.        * processes.
  756.        */
  757.       result = ENOSYS;
  758.       goto FAIL0;
  759.     }
  760.   cv = (pthread_cond_t) calloc (1, sizeof (*cv));
  761.   if (cv == NULL)
  762.     {(cv
  763.       result = ENOMEM;
  764.       goto FAIL0;
  765.     }
  766.   cv->nWaitersBlocked   = 0;
  767.   cv->nWaitersUnblocked = 0;
  768.   cv->nWaitersToUnblock = 0;
  769.   if (sem_init (&(cv->semBlockLock), 0, 1) != 0)
  770.     {(sem_init
  771.       goto FAIL0;
  772.     }
  773.   if (sem_init (&(cv->semBlockQueue), 0, 0) != 0)
  774.     {(sem_init
  775.       goto FAIL1;
  776.     }
  777.   if (pthread_mutex_init (&(cv->mtxUnblockLock), 0) != 0)
  778.     {(pthread_mutex_init
  779.       goto FAIL2;
  780.     }
  781.   result = 0;
  782.   goto DONE;
  783.   /*
  784.    * -------------
  785.    * Failed...
  786.    * -------------
  787.    */
  788. FAIL2:
  789.   (void) sem_destroy (&(cv->semBlockQueue));
  790. FAIL1:
  791.   (void) sem_destroy (&(cv->semBlockLock));
  792. FAIL0:
  793. DONE:
  794.   *cond = cv;
  795.   return (result);
  796. }                               /* pthread_cond_init */
  797. int
  798. pthread_cond_destroy (pthread_cond_t * cond)
  799. {
  800.   int result = 0;
  801.   pthread_cond_t cv;
  802.   /*
  803.    * Assuming any race condition here is harmless.
  804.    */
  805.   if (cond == NULL
  806.       || *cond == NULL)
  807.     {
  808.       return EINVAL;
  809.     }
  810.   if (*cond != (pthread_cond_t) PTW32_OBJECT_AUTO_INIT)
  811.     {(*cond
  812.       cv = *cond;
  813.       /*
  814.        * Synchronize access to waiters blocked count (LEVEL-1)
  815.        */
  816.       if (sem_wait(&(cv->semBlockLock)) != 0)
  817.         {(sem_wait(&(cv->semBlockLock))
  818.           return errno;
  819.         }
  820.       /*
  821.        * Synchronize access to waiters (to)unblock(ed) counts (LEVEL-2)
  822.        */
  823.       if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0)
  824.         {((result
  825.           (void) sem_post(&(cv->semBlockLock));
  826.           return result;
  827.         }
  828.       /*
  829.        * Check whether cv is still busy (still has waiters blocked)
  830.        */
  831.       if (cv->nWaitersBlocked - cv->nWaitersUnblocked > 0)
  832.         {(cv->nWaitersBlocked
  833.           (void) sem_post(&(cv->semBlockLock));
  834.           (void) pthread_mutex_unlock(&(cv->mtxUnblockLock));
  835.           return EBUSY;
  836.         }
  837.       /*
  838.        * Now it is safe to destroy
  839.        */
  840.       (void) sem_destroy (&(cv->semBlockLock));
  841.       (void) sem_destroy (&(cv->semBlockQueue));
  842.       (void) pthread_mutex_unlock (&(cv->mtxUnblockLock));
  843.       (void) pthread_mutex_destroy (&(cv->mtxUnblockLock));
  844.       free(cv);
  845.       *cond = NULL;
  846.     }
  847.   else
  848.     {
  849.       /*
  850.        * See notes in ptw32_cond_check_need_init() above also.
  851.        */
  852.       EnterCriticalSection(&ptw32_cond_test_init_lock);
  853.       /*
  854.        * Check again.
  855.        */
  856.       if (*cond == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT)
  857.         {(*cond
  858.           /*
  859.            * This is all we need to do to destroy a statically
  860.            * initialised cond that has not yet been used (initialised).
  861.            * If we get to here, another thread
  862.            * waiting to initialise this cond will get an EINVAL.
  863.            */
  864.           *cond = NULL;
  865.         }
  866.       else
  867.         {
  868.           /*
  869.            * The cv has been initialised while we were waiting
  870.            * so assume it's in use.
  871.            */
  872.           result = EBUSY;
  873.         }
  874.       LeaveCriticalSection(&ptw32_cond_test_init_lock);
  875.     }
  876.   return (result);
  877. }
  878. /*
  879.  * Arguments for cond_wait_cleanup, since we can only pass a
  880.  * single void * to it.
  881.  */
  882. typedef struct {
  883.   pthread_mutex_t * mutexPtr;
  884.   pthread_cond_t cv;
  885.   int * resultPtr;
  886. } ptw32_cond_wait_cleanup_args_t;
  887. static void
  888. ptw32_cond_wait_cleanup(void * args)
  889. {
  890.   ptw32_cond_wait_cleanup_args_t * cleanup_args =
  891. (ptw32_cond_wait_cleanup_args_t *) args;
  892.   pthread_cond_t cv = cleanup_args->cv;
  893.   int * resultPtr = cleanup_args->resultPtr;
  894.   int eLastSignal; /* enum: 1=yes 0=no -1=cancelled/timedout w/o signal(s)
  895. */
  896.   int result;
  897.   /*
  898.    * Whether we got here as a result of signal/broadcast or because of
  899.    * timeout on wait or thread cancellation we indicate that we are no
  900.    * longer waiting. The waiter is responsible for adjusting waiters
  901.    * (to)unblock(ed) counts (protected by unblock lock).
  902.    * Unblock lock/Sync.LEVEL-2 supports _timedwait and cancellation.
  903.    */
  904.   if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0)
  905.     {((result
  906.       *resultPtr = result;
  907.       return;
  908.     }
  909.   cv->nWaitersUnblocked++;
  910.   eLastSignal = (cv->nWaitersToUnblock == 0) ?
  911.                    -1 : (--cv->nWaitersToUnblock == 0);
  912.   /*
  913.    * No more LEVEL-2 access to waiters (to)unblock(ed) counts needed
  914.    */
  915.   if ((result = pthread_mutex_unlock(&(cv->mtxUnblockLock))) != 0)
  916.     {((result
  917.       *resultPtr = result;
  918.       return;
  919.     }
  920.   /*
  921.    * If last signal...
  922.    */
  923.   if (eLastSignal == 1)
  924.     {(eLastSignal
  925.      /*
  926.       * ...it means that we have end of 'atomic' signal/broadcast
  927.       */
  928.       if (sem_post(&(cv->semBlockLock)) != 0)
  929.         {(sem_post(&(cv->semBlockLock))
  930.           *resultPtr = errno;
  931.           return;
  932.         }
  933.     }
  934.   /*
  935.    * If not last signal and not timed out/cancelled wait w/o signal...
  936.    */
  937.   else if (eLastSignal == 0)
  938.     {
  939.      /*
  940.       * ...it means that next waiter can go through semaphore
  941.       */
  942.       if (sem_post(&(cv->semBlockQueue)) != 0)
  943.         {(sem_post(&(cv->semBlockQueue))
  944.           *resultPtr = errno;
  945.           return;
  946.         }
  947.     }
  948.   /*
  949.    * XSH: Upon successful return, the mutex has been locked and is owned
  950.    * by the calling thread
  951.    */
  952.   if ((result = pthread_mutex_lock(cleanup_args->mutexPtr)) != 0)
  953.     {((result
  954.       *resultPtr = result;
  955.     }
  956. }                               /* ptw32_cond_wait_cleanup */
  957. static int
  958. ptw32_cond_timedwait (pthread_cond_t * cond,
  959.                       pthread_mutex_t * mutex,
  960.                       const struct timespec *abstime)
  961. {
  962.   int result = 0;
  963.   pthread_cond_t cv;
  964.   ptw32_cond_wait_cleanup_args_t cleanup_args;
  965.   if (cond == NULL || *cond == NULL)
  966.     {(cond
  967.       return EINVAL;
  968.     }
  969.   /*
  970.    * We do a quick check to see if we need to do more work
  971.    * to initialise a static condition variable. We check
  972.    * again inside the guarded section of ptw32_cond_check_need_init()
  973.    * to avoid race conditions.
  974.    */
  975.   if (*cond == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT)
  976.     {(*cond
  977.       result = ptw32_cond_check_need_init(cond);
  978.     }
  979.   if (result != 0 && result != EBUSY)
  980.     {(result
  981.       return result;
  982.     }
  983.   cv = *cond;
  984.   /*
  985.    * Synchronize access to waiters blocked count (LEVEL-1)
  986.    */
  987.   if (sem_wait(&(cv->semBlockLock)) != 0)
  988.     {(sem_wait(&(cv->semBlockLock))
  989.       return errno;
  990.     }
  991.   cv->nWaitersBlocked++;
  992.   /*
  993.    * Thats it. Counted means waiting, no more access needed
  994.    */
  995.   if (sem_post(&(cv->semBlockLock)) != 0)
  996.     {(sem_post(&(cv->semBlockLock))
  997.       return errno;
  998.     }
  999.   /*
  1000.    * Setup this waiter cleanup handler
  1001.    */
  1002.   cleanup_args.mutexPtr = mutex;
  1003.   cleanup_args.cv = cv;
  1004.   cleanup_args.resultPtr = &result;
  1005.   pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *) &cleanup_args);
  1006.   /*
  1007.    * Now we can release 'mutex' and...
  1008.    */
  1009.   if ((result = pthread_mutex_unlock (mutex)) == 0)
  1010.     {((result
  1011.       /*
  1012.        * ...wait to be awakened by
  1013.        *              pthread_cond_signal, or
  1014.        *              pthread_cond_broadcast, or
  1015.        *              timeout, or
  1016.        *              thread cancellation
  1017.        *
  1018.        * Note:
  1019.        *
  1020.        *      ptw32_sem_timedwait is a cancellation point,
  1021.        *      hence providing the mechanism for making
  1022.        *      pthread_cond_wait a cancellation point.
  1023.        *      We use the cleanup mechanism to ensure we
  1024.        *      re-lock the mutex and adjust (to)unblock(ed) waiters
  1025.        *      counts if we are cancelled, timed out or signalled.
  1026.        */
  1027.       if (ptw32_sem_timedwait (&(cv->semBlockQueue), abstime) != 0)
  1028.         {(ptw32_sem_timedwait
  1029.           result = errno;
  1030.         }
  1031.     }
  1032.   /*
  1033.    * Always cleanup
  1034.    */
  1035.   pthread_cleanup_pop (1);
  1036.   /*
  1037.    * "result" can be modified by the cleanup handler.
  1038.    */
  1039.   return (result);
  1040. }                               /* ptw32_cond_timedwait */
  1041. static int
  1042. ptw32_cond_unblock (pthread_cond_t * cond,
  1043.                     int unblockAll)
  1044. {
  1045.   int result;
  1046.   pthread_cond_t cv;
  1047.   if (cond == NULL || *cond == NULL)
  1048.     {(cond
  1049.       return EINVAL;
  1050.     }
  1051.   cv = *cond;
  1052.   /*
  1053.    * No-op if the CV is static and hasn't been initialised yet.
  1054.    * Assuming that any race condition is harmless.
  1055.    */
  1056.   if (cv == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT)
  1057.     {(cv
  1058.       return 0;
  1059.     }
  1060.   /*
  1061.    * Synchronize access to waiters blocked count (LEVEL-1)
  1062.    */
  1063.   if (sem_wait(&(cv->semBlockLock)) != 0)
  1064.     {(sem_wait(&(cv->semBlockLock))
  1065.       return errno;
  1066.     }
  1067.   /*
  1068.    * Synchronize access to waiters (to)unblock(ed) counts (LEVEL-2)
  1069.    * This sync.level supports _timedwait and cancellation
  1070.    */
  1071.   if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0)
  1072.     {((result
  1073.       return result;
  1074.     }
  1075.   /*
  1076.    * Adjust waiters blocked and unblocked counts (collect garbage)
  1077.    */
  1078.   if (cv->nWaitersUnblocked != 0)
  1079.     {(cv->nWaitersUnblocked
  1080.       cv->nWaitersBlocked  -= cv->nWaitersUnblocked;
  1081.       cv->nWaitersUnblocked = 0;
  1082.     }
  1083.   /*
  1084.    * If (after adjustment) there are still some waiters blocked counted...
  1085.    */
  1086.   if ( cv->nWaitersBlocked > 0)
  1087.     {(
  1088.       /*
  1089.        * We will unblock first waiter and leave semBlockLock/LEVEL-1 locked
  1090.        * LEVEL-1 access is left disabled until last signal/unblock
  1091. completes
  1092.        */
  1093.       cv->nWaitersToUnblock = (unblockAll) ? cv->nWaitersBlocked : 1;
  1094.       /*
  1095.        * No more LEVEL-2 access to waiters (to)unblock(ed) counts needed
  1096.        * This sync.level supports _timedwait and cancellation
  1097.        */
  1098.       if ((result = pthread_mutex_unlock(&(cv->mtxUnblockLock))) != 0)
  1099.         {((result
  1100.           return result;
  1101.         }
  1102.       /*
  1103.        * Now, with LEVEL-2 lock released let first waiter go through
  1104. semaphore
  1105.        */
  1106.       if (sem_post(&(cv->semBlockQueue)) != 0)
  1107.         {(sem_post(&(cv->semBlockQueue))
  1108.           return errno;
  1109.         }
  1110.     }
  1111.   /*
  1112.    * No waiter blocked - no more LEVEL-1 access to blocked count needed...
  1113.    */
  1114.   else if (sem_post(&(cv->semBlockLock)) != 0)
  1115.     {
  1116.       return errno;
  1117.     }
  1118.   /*
  1119.    * ...and no more LEVEL-2 access to waiters (to)unblock(ed) counts needed
  1120. too
  1121.    * This sync.level supports _timedwait and cancellation
  1122.    */
  1123.   else
  1124.     {
  1125.       result = pthread_mutex_unlock(&(cv->mtxUnblockLock));
  1126.     }
  1127.   return(result);
  1128. }                               /* ptw32_cond_unblock */
  1129. int
  1130. pthread_cond_wait (pthread_cond_t * cond,
  1131.                    pthread_mutex_t * mutex)
  1132. {
  1133.   /* The NULL abstime arg means INFINITE waiting. */
  1134.   return(ptw32_cond_timedwait(cond, mutex, NULL));
  1135. }                               /* pthread_cond_wait */
  1136. int
  1137. pthread_cond_timedwait (pthread_cond_t * cond,
  1138.                         pthread_mutex_t * mutex,
  1139.                         const struct timespec *abstime)
  1140. {
  1141.   if (abstime == NULL)
  1142.     {(abstime
  1143.       return EINVAL;
  1144.     }
  1145.   return(ptw32_cond_timedwait(cond, mutex, abstime));
  1146. }                               /* pthread_cond_timedwait */
  1147. int
  1148. pthread_cond_signal (pthread_cond_t * cond)
  1149. {
  1150.   /* The '0'(FALSE) unblockAll arg means unblock ONE waiter. */
  1151.   return(ptw32_cond_unblock(cond, 0));
  1152. }                               /* pthread_cond_signal */
  1153. int
  1154. pthread_cond_broadcast (pthread_cond_t * cond)
  1155. {
  1156.   /* The '1'(TRUE) unblockAll arg means unblock ALL waiters. */
  1157.   return(ptw32_cond_unblock(cond, 1));
  1158. }                               /* pthread_cond_broadcast */
  1159. TEREKHOV@de.ibm.com on 17.01.2001 01:00:57
  1160. Please respond to TEREKHOV@de.ibm.com
  1161. To:   pthreads-win32@sourceware.cygnus.com
  1162. cc:   schmidt@uci.edu
  1163. Subject:  win32 conditions: sem+counter+event = broadcast_deadlock +
  1164.       spur.wakeup/unfairness/incorrectness ??
  1165. Hi,
  1166. Problem 1: broadcast_deadlock
  1167. It seems that current implementation does not provide "atomic"
  1168. broadcasts. That may lead to "nested" broadcasts... and it seems
  1169. that nested case is not handled correctly -> producing a broadcast
  1170. DEADLOCK as a result.
  1171. Scenario:
  1172. N (>1) waiting threads W1..N are blocked (in _wait) on condition's
  1173. semaphore.
  1174. Thread B1 calls pthread_cond_broadcast, which results in "releasing" N
  1175. W threads via incrementing semaphore counter by N (stored in
  1176. cv->waiters) BUT cv->waiters counter does not change!! The caller
  1177. thread B1 remains blocked on cv->waitersDone event (auto-reset!!) BUT
  1178. condition is not protected from starting another broadcast (when called
  1179. on another thread) while still waiting for the "old" broadcast to
  1180. complete on thread B1.
  1181. M (>=0, <N) W threads are fast enough to go thru their _wait call and
  1182. decrement cv->waiters counter.
  1183. L (N-M) "late" waiter W threads are a) still blocked/not returned from
  1184. their semaphore wait call or b) were preempted after sem_wait but before
  1185. lock( &cv->waitersLock ) or c) are blocked on cv->waitersLock.
  1186. cv->waiters is still > 0 (= L).
  1187. Another thread B2 (or some W thread from M group) calls
  1188. pthread_cond_broadcast and gains access to counter... neither a) nor b)
  1189. prevent thread B2 in pthread_cond_broadcast from gaining access to
  1190. counter and starting another broadcast ( for c) - it depends on
  1191. cv->waitersLock scheduling rules: FIFO=OK, PRTY=PROBLEM,... )
  1192. That call to pthread_cond_broadcast (on thread B2) will result in
  1193. incrementing semaphore by cv->waiters (=L) which is INCORRECT (all
  1194. W1..N were in fact already released by thread B1) and waiting on
  1195. _auto-reset_ event cv->waitersDone which is DEADLY WRONG (produces a
  1196. deadlock)...
  1197. All late W1..L threads now have a chance to complete their _wait call.
  1198. Last W_L thread sets an auto-reselt event cv->waitersDone which will
  1199. release either B1 or B2 leaving one of B threads in a deadlock.
  1200. Problem 2: spur.wakeup/unfairness/incorrectness
  1201. It seems that:
  1202. a) because of the same problem with counter which does not reflect the
  1203. actual number of NOT RELEASED waiters, the signal call may increment
  1204. a semaphore counter w/o having a waiter blocked on it. That will result
  1205. in (best case) spurious wake ups - performance degradation due to
  1206. unnecessary context switches and predicate re-checks and (in worth case)
  1207. unfairness/incorrectness problem - see b)
  1208. b) neither signal nor broadcast prevent other threads - "new waiters"
  1209. (and in the case of signal, the caller thread as well) from going into
  1210. _wait and overtaking "old" waiters (already released but still not returned
  1211. from sem_wait on condition's semaphore). Win semaphore just [API DOC]:
  1212. "Maintains a count between zero and some maximum value, limiting the number
  1213. of threads that are simultaneously accessing a shared resource." Calling
  1214. ReleaseSemaphore does not imply (at least not documented) that on return
  1215. from ReleaseSemaphore all waiters will in fact become released (returned
  1216. from their Wait... call) and/or that new waiters calling Wait... afterwards
  1217. will become less importance. It is NOT documented to be an atomic release
  1218. of
  1219. waiters... And even if it would be there is still a problem with a thread
  1220. being preempted after Wait on semaphore and before Wait on cv->waitersLock
  1221. and scheduling rules for cv->waitersLock itself
  1222. (??WaitForMultipleObjects??)
  1223. That may result in unfairness/incorrectness problem as described
  1224. for SetEvent impl. in "Strategies for Implementing POSIX Condition
  1225. Variables
  1226. on Win32": http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  1227. Unfairness -- The semantics of the POSIX pthread_cond_broadcast function is
  1228. to wake up all threads currently blocked in wait calls on the condition
  1229. variable. The awakened threads then compete for the external_mutex. To
  1230. ensure
  1231. fairness, all of these threads should be released from their
  1232. pthread_cond_wait calls and allowed to recheck their condition expressions
  1233. before other threads can successfully complete a wait on the condition
  1234. variable.
  1235. Unfortunately, the SetEvent implementation above does not guarantee that
  1236. all
  1237. threads sleeping on the condition variable when cond_broadcast is called
  1238. will
  1239. acquire the external_mutex and check their condition expressions. Although
  1240. the Pthreads specification does not mandate this degree of fairness, the
  1241. lack of fairness can cause starvation.
  1242. To illustrate the unfairness problem, imagine there are 2 threads, C1 and
  1243. C2,
  1244. that are blocked in pthread_cond_wait on condition variable not_empty_ that
  1245. is guarding a thread-safe message queue. Another thread, P1 then places two
  1246. messages onto the queue and calls pthread_cond_broadcast. If C1 returns
  1247. from
  1248. pthread_cond_wait, dequeues and processes the message, and immediately
  1249. waits
  1250. again then it and only it may end up acquiring both messages. Thus, C2 will
  1251. never get a chance to dequeue a message and run.
  1252. The following illustrates the sequence of events:
  1253. 1.   Thread C1 attempts to dequeue and waits on CV non_empty_
  1254. 2.   Thread C2 attempts to dequeue and waits on CV non_empty_
  1255. 3.   Thread P1 enqueues 2 messages and broadcasts to CV not_empty_
  1256. 4.   Thread P1 exits
  1257. 5.   Thread C1 wakes up from CV not_empty_, dequeues a message and runs
  1258. 6.   Thread C1 waits again on CV not_empty_, immediately dequeues the 2nd
  1259.         message and runs
  1260. 7.   Thread C1 exits
  1261. 8.   Thread C2 is the only thread left and blocks forever since
  1262.         not_empty_ will never be signaled
  1263. Depending on the algorithm being implemented, this lack of fairness may
  1264. yield
  1265. concurrent programs that have subtle bugs. Of course, application
  1266. developers
  1267. should not rely on the fairness semantics of pthread_cond_broadcast.
  1268. However,
  1269. there are many cases where fair implementations of condition variables can
  1270. simplify application code.
  1271. Incorrectness -- A variation on the unfairness problem described above
  1272. occurs
  1273. when a third consumer thread, C3, is allowed to slip through even though it
  1274. was not waiting on condition variable not_empty_ when a broadcast occurred.
  1275. To illustrate this, we will use the same scenario as above: 2 threads, C1
  1276. and
  1277. C2, are blocked dequeuing messages from the message queue. Another thread,
  1278. P1
  1279. then places two messages onto the queue and calls pthread_cond_broadcast.
  1280. C1
  1281. returns from pthread_cond_wait, dequeues and processes the message. At this
  1282. time, C3 acquires the external_mutex, calls pthread_cond_wait and waits on
  1283. the events in WaitForMultipleObjects. Since C2 has not had a chance to run
  1284. yet, the BROADCAST event is still signaled. C3 then returns from
  1285. WaitForMultipleObjects, and dequeues and processes the message in the
  1286. queue.
  1287. Thus, C2 will never get a chance to dequeue a message and run.
  1288. The following illustrates the sequence of events:
  1289. 1.   Thread C1 attempts to dequeue and waits on CV non_empty_
  1290. 2.   Thread C2 attempts to dequeue and waits on CV non_empty_
  1291. 3.   Thread P1 enqueues 2 messages and broadcasts to CV not_empty_
  1292. 4.   Thread P1 exits
  1293. 5.   Thread C1 wakes up from CV not_empty_, dequeues a message and runs
  1294. 6.   Thread C1 exits
  1295. 7.   Thread C3 waits on CV not_empty_, immediately dequeues the 2nd
  1296.         message and runs
  1297. 8.   Thread C3 exits
  1298. 9.   Thread C2 is the only thread left and blocks forever since
  1299.         not_empty_ will never be signaled
  1300. In the above case, a thread that was not waiting on the condition variable
  1301. when a broadcast occurred was allowed to proceed. This leads to incorrect
  1302. semantics for a condition variable.
  1303. COMMENTS???
  1304. regards,
  1305. alexander.
  1306. -----------------------------------------------------------------------------
  1307. Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_*
  1308.      implementation questions
  1309. Date: Wed, 21 Feb 2001 11:54:47 +0100
  1310. From: TEREKHOV@de.ibm.com
  1311. To: lthomas@arbitrade.com
  1312. CC: rpj@ise.canberra.edu.au, Thomas Pfaff <tpfaff@gmx.net>,
  1313.      Nanbor Wang <nanbor@cs.wustl.edu>
  1314. Hi Louis,
  1315. generation number 8..
  1316. had some time to revisit timeouts/spurious wakeup problem..
  1317. found some bugs (in 7.b/c/d) and something to improve
  1318. (7a - using IPC semaphores but it should speedup Win32
  1319. version as well).
  1320. regards,
  1321. alexander.
  1322. ---------- Algorithm 8a / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ALL ------
  1323. given:
  1324. semBlockLock - bin.semaphore
  1325. semBlockQueue - semaphore
  1326. mtxExternal - mutex or CS
  1327. mtxUnblockLock - mutex or CS
  1328. nWaitersGone - int
  1329. nWaitersBlocked - int
  1330. nWaitersToUnblock - int
  1331. wait( timeout ) {
  1332.   [auto: register int result          ]     // error checking omitted
  1333.   [auto: register int nSignalsWasLeft ]
  1334.   [auto: register int nWaitersWasGone ]
  1335.   sem_wait( semBlockLock );
  1336.   nWaitersBlocked++;
  1337.   sem_post( semBlockLock );
  1338.   unlock( mtxExternal );
  1339.   bTimedOut = sem_wait( semBlockQueue,timeout );
  1340.   lock( mtxUnblockLock );
  1341.   if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) {
  1342.     if ( bTimeout ) {                       // timeout (or canceled)
  1343.       if ( 0 != nWaitersBlocked ) {
  1344.         nWaitersBlocked--;
  1345.       }
  1346.       else {
  1347.         nWaitersGone++;                     // count spurious wakeups
  1348.       }
  1349.     }
  1350.     if ( 0 == --nWaitersToUnblock ) {
  1351.       if ( 0 != nWaitersBlocked ) {
  1352.         sem_post( semBlockLock );           // open the gate
  1353.         nSignalsWasLeft = 0;                // do not open the gate below
  1354. again
  1355.       }
  1356.       else if ( 0 != (nWaitersWasGone = nWaitersGone) ) {
  1357.         nWaitersGone = 0;
  1358.       }
  1359.     }
  1360.   }
  1361.   else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious
  1362. semaphore :-)
  1363.     sem_wait( semBlockLock );
  1364.     nWaitersBlocked -= nWaitersGone;        // something is going on here -
  1365. test of timeouts? :-)
  1366.     sem_post( semBlockLock );
  1367.     nWaitersGone = 0;
  1368.   }
  1369.   unlock( mtxUnblockLock );
  1370.   if ( 1 == nSignalsWasLeft ) {
  1371.     if ( 0 != nWaitersWasGone ) {
  1372.       // sem_adjust( -nWaitersWasGone );
  1373.       while ( nWaitersWasGone-- ) {
  1374.         sem_wait( semBlockLock );          // better now than spurious
  1375. later
  1376.       }
  1377.     }
  1378.     sem_post( semBlockLock );              // open the gate
  1379.   }
  1380.   lock( mtxExternal );
  1381.   return ( bTimedOut ) ? ETIMEOUT : 0;
  1382. }
  1383. signal(bAll) {
  1384.   [auto: register int result         ]
  1385.   [auto: register int nSignalsToIssue]
  1386.   lock( mtxUnblockLock );
  1387.   if ( 0 != nWaitersToUnblock ) { // the gate is closed!!!
  1388.     if ( 0 == nWaitersBlocked ) { // NO-OP
  1389.       return unlock( mtxUnblockLock );
  1390.     }
  1391.     if (bAll) {
  1392.       nWaitersToUnblock += nSignalsToIssue=nWaitersBlocked;
  1393.       nWaitersBlocked = 0;
  1394.     }
  1395.     else {
  1396.       nSignalsToIssue = 1;
  1397.       nWaitersToUnblock++;
  1398.       nWaitersBlocked--;
  1399.     }
  1400.   }
  1401.   else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION!
  1402.     sem_wait( semBlockLock ); // close the gate
  1403.     if ( 0 != nWaitersGone ) {
  1404.       nWaitersBlocked -= nWaitersGone;
  1405.       nWaitersGone = 0;
  1406.     }
  1407.     if (bAll) {
  1408.       nSignalsToIssue = nWaitersToUnblock = nWaitersBlocked;
  1409.       nWaitersBlocked = 0;
  1410.     }
  1411.     else {
  1412.       nSignalsToIssue = nWaitersToUnblock = 1;
  1413.       nWaitersBlocked--;
  1414.     }
  1415.   }
  1416.   else { // NO-OP
  1417.     return unlock( mtxUnblockLock );
  1418.   }
  1419.   unlock( mtxUnblockLock );
  1420.   sem_post( semBlockQueue,nSignalsToIssue );
  1421.   return result;
  1422. }
  1423. ---------- Algorithm 8b / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ONEBYONE
  1424. ------
  1425. given:
  1426. semBlockLock - bin.semaphore
  1427. semBlockQueue - bin.semaphore
  1428. mtxExternal - mutex or CS
  1429. mtxUnblockLock - mutex or CS
  1430. nWaitersGone - int
  1431. nWaitersBlocked - int
  1432. nWaitersToUnblock - int
  1433. wait( timeout ) {
  1434.   [auto: register int result          ]     // error checking omitted
  1435.   [auto: register int nWaitersWasGone ]
  1436.   [auto: register int nSignalsWasLeft ]
  1437.   sem_wait( semBlockLock );
  1438.   nWaitersBlocked++;
  1439.   sem_post( semBlockLock );
  1440.   unlock( mtxExternal );
  1441.   bTimedOut = sem_wait( semBlockQueue,timeout );
  1442.   lock( mtxUnblockLock );
  1443.   if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) {
  1444.     if ( bTimeout ) {                       // timeout (or canceled)
  1445.       if ( 0 != nWaitersBlocked ) {
  1446.         nWaitersBlocked--;
  1447.         nSignalsWasLeft = 0;                // do not unblock next waiter
  1448. below (already unblocked)
  1449.       }
  1450.       else {
  1451.         nWaitersGone = 1;                   // spurious wakeup pending!!
  1452.       }
  1453.     }
  1454.     if ( 0 == --nWaitersToUnblock &&
  1455.       if ( 0 != nWaitersBlocked ) {
  1456.         sem_post( semBlockLock );           // open the gate
  1457.         nSignalsWasLeft = 0;                // do not open the gate below
  1458. again
  1459.       }
  1460.       else if ( 0 != (nWaitersWasGone = nWaitersGone) ) {
  1461.         nWaitersGone = 0;
  1462.       }
  1463.     }
  1464.   }
  1465.   else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious
  1466. semaphore :-)
  1467.     sem_wait( semBlockLock );
  1468.     nWaitersBlocked -= nWaitersGone;        // something is going on here -
  1469. test of timeouts? :-)
  1470.     sem_post( semBlockLock );
  1471.     nWaitersGone = 0;
  1472.   }
  1473.   unlock( mtxUnblockLock );
  1474.   if ( 1 == nSignalsWasLeft ) {
  1475.     if ( 0 != nWaitersWasGone ) {
  1476.       // sem_adjust( -1 );
  1477.       sem_wait( semBlockQueue );           // better now than spurious
  1478. later
  1479.     }
  1480.     sem_post( semBlockLock );              // open the gate
  1481.   }
  1482.   else if ( 0 != nSignalsWasLeft ) {
  1483.     sem_post( semBlockQueue );             // unblock next waiter
  1484.   }
  1485.   lock( mtxExternal );
  1486.   return ( bTimedOut ) ? ETIMEOUT : 0;
  1487. }
  1488. signal(bAll) {
  1489.   [auto: register int result ]
  1490.   lock( mtxUnblockLock );
  1491.   if ( 0 != nWaitersToUnblock ) { // the gate is closed!!!
  1492.     if ( 0 == nWaitersBlocked ) { // NO-OP
  1493.       return unlock( mtxUnblockLock );
  1494.     }
  1495.     if (bAll) {
  1496.       nWaitersToUnblock += nWaitersBlocked;
  1497.       nWaitersBlocked = 0;
  1498.     }
  1499.     else {
  1500.       nWaitersToUnblock++;
  1501.       nWaitersBlocked--;
  1502.     }
  1503.     unlock( mtxUnblockLock );
  1504.   }
  1505.   else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION!
  1506.     sem_wait( semBlockLock ); // close the gate
  1507.     if ( 0 != nWaitersGone ) {
  1508.       nWaitersBlocked -= nWaitersGone;
  1509.       nWaitersGone = 0;
  1510.     }
  1511.     if (bAll) {
  1512.       nWaitersToUnblock = nWaitersBlocked;
  1513.       nWaitersBlocked = 0;
  1514.     }
  1515.     else {
  1516.       nWaitersToUnblock = 1;
  1517.       nWaitersBlocked--;
  1518.     }
  1519.     unlock( mtxUnblockLock );
  1520.     sem_post( semBlockQueue );
  1521.   }
  1522.   else { // NO-OP
  1523.     unlock( mtxUnblockLock );
  1524.   }
  1525.   return result;
  1526. }
  1527. ---------- Algorithm 8c / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ONEBYONE
  1528. ---------
  1529. given:
  1530. hevBlockLock - auto-reset event
  1531. hevBlockQueue - auto-reset event
  1532. mtxExternal - mutex or CS
  1533. mtxUnblockLock - mutex or CS
  1534. nWaitersGone - int
  1535. nWaitersBlocked - int
  1536. nWaitersToUnblock - int
  1537. wait( timeout ) {
  1538.   [auto: register int result          ]     // error checking omitted
  1539.   [auto: register int nSignalsWasLeft ]
  1540.   [auto: register int nWaitersWasGone ]
  1541.   wait( hevBlockLock,INFINITE );
  1542.   nWaitersBlocked++;
  1543.   set_event( hevBlockLock );
  1544.   unlock( mtxExternal );
  1545.   bTimedOut = wait( hevBlockQueue,timeout );
  1546.   lock( mtxUnblockLock );
  1547.   if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) {
  1548.     if ( bTimeout ) {                       // timeout (or canceled)
  1549.       if ( 0 != nWaitersBlocked ) {
  1550.         nWaitersBlocked--;
  1551.         nSignalsWasLeft = 0;                // do not unblock next waiter
  1552. below (already unblocked)
  1553.       }
  1554.       else {
  1555.         nWaitersGone = 1;                   // spurious wakeup pending!!
  1556.       }
  1557.     }
  1558.     if ( 0 == --nWaitersToUnblock )
  1559.       if ( 0 != nWaitersBlocked ) {
  1560.         set_event( hevBlockLock );          // open the gate
  1561.         nSignalsWasLeft = 0;                // do not open the gate below
  1562. again
  1563.       }
  1564.       else if ( 0 != (nWaitersWasGone = nWaitersGone) ) {
  1565.         nWaitersGone = 0;
  1566.       }
  1567.     }
  1568.   }
  1569.   else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious
  1570. event :-)
  1571.     wait( hevBlockLock,INFINITE );
  1572.     nWaitersBlocked -= nWaitersGone;        // something is going on here -
  1573. test of timeouts? :-)
  1574.     set_event( hevBlockLock );
  1575.     nWaitersGone = 0;
  1576.   }
  1577.   unlock( mtxUnblockLock );
  1578.   if ( 1 == nSignalsWasLeft ) {
  1579.     if ( 0 != nWaitersWasGone ) {
  1580.       reset_event( hevBlockQueue );         // better now than spurious
  1581. later
  1582.     }
  1583.     set_event( hevBlockLock );              // open the gate
  1584.   }
  1585.   else if ( 0 != nSignalsWasLeft ) {
  1586.     set_event( hevBlockQueue );             // unblock next waiter
  1587.   }
  1588.   lock( mtxExternal );
  1589.   return ( bTimedOut ) ? ETIMEOUT : 0;
  1590. }
  1591. signal(bAll) {
  1592.   [auto: register int result ]
  1593.   lock( mtxUnblockLock );
  1594.   if ( 0 != nWaitersToUnblock ) { // the gate is closed!!!
  1595.     if ( 0 == nWaitersBlocked ) { // NO-OP
  1596.       return unlock( mtxUnblockLock );
  1597.     }
  1598.     if (bAll) {
  1599.       nWaitersToUnblock += nWaitersBlocked;
  1600.       nWaitersBlocked = 0;
  1601.     }
  1602.     else {
  1603.       nWaitersToUnblock++;
  1604.       nWaitersBlocked--;
  1605.     }
  1606.     unlock( mtxUnblockLock );
  1607.   }
  1608.   else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION!
  1609.     wait( hevBlockLock,INFINITE ); // close the gate
  1610.     if ( 0 != nWaitersGone ) {
  1611.       nWaitersBlocked -= nWaitersGone;
  1612.       nWaitersGone = 0;
  1613.     }
  1614.     if (bAll) {
  1615.       nWaitersToUnblock = nWaitersBlocked;
  1616.       nWaitersBlocked = 0;
  1617.     }
  1618.     else {
  1619.       nWaitersToUnblock = 1;
  1620.       nWaitersBlocked--;
  1621.     }
  1622.     unlock( mtxUnblockLock );
  1623.     set_event( hevBlockQueue );
  1624.   }
  1625.   else { // NO-OP
  1626.     unlock( mtxUnblockLock );
  1627.   }
  1628.   return result;
  1629. }
  1630. ---------- Algorithm 8d / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ALL ------
  1631. given:
  1632. hevBlockLock - auto-reset event
  1633. hevBlockQueueS - auto-reset event  // for signals
  1634. hevBlockQueueB - manual-reset even // for broadcasts
  1635. mtxExternal - mutex or CS
  1636. mtxUnblockLock - mutex or CS
  1637. eBroadcast - int                   // 0: no broadcast, 1: broadcast, 2:
  1638. broadcast after signal(s)
  1639. nWaitersGone - int
  1640. nWaitersBlocked - int
  1641. nWaitersToUnblock - int
  1642. wait( timeout ) {
  1643.   [auto: register int result          ]     // error checking omitted
  1644.   [auto: register int eWasBroadcast   ]
  1645.   [auto: register int nSignalsWasLeft ]
  1646.   [auto: register int nWaitersWasGone ]
  1647.   wait( hevBlockLock,INFINITE );
  1648.   nWaitersBlocked++;
  1649.   set_event( hevBlockLock );
  1650.   unlock( mtxExternal );
  1651.   bTimedOut = waitformultiple( hevBlockQueueS,hevBlockQueueB,timeout,ONE );
  1652.   lock( mtxUnblockLock );
  1653.   if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) {
  1654.     if ( bTimeout ) {                       // timeout (or canceled)
  1655.       if ( 0 != nWaitersBlocked ) {
  1656.         nWaitersBlocked--;
  1657.         nSignalsWasLeft = 0;                // do not unblock next waiter
  1658. below (already unblocked)
  1659.       }
  1660.       else if ( 1 != eBroadcast ) {
  1661.         nWaitersGone = 1;
  1662.       }
  1663.     }
  1664.     if ( 0 == --nWaitersToUnblock ) {
  1665.       if ( 0 != nWaitersBlocked ) {
  1666.         set_event( hevBlockLock );           // open the gate
  1667.         nSignalsWasLeft = 0;                 // do not open the gate below
  1668. again
  1669.       }
  1670.       else {
  1671.         if ( 0 != (eWasBroadcast = eBroadcast) ) {
  1672.           eBroadcast = 0;
  1673.         }
  1674.         if ( 0 != (nWaitersWasGone = nWaitersGone ) {
  1675.           nWaitersGone = 0;
  1676.         }
  1677.       }
  1678.     }
  1679.     else if ( 0 != eBroadcast ) {
  1680.       nSignalsWasLeft = 0;                  // do not unblock next waiter
  1681. below (already unblocked)
  1682.     }
  1683.   }
  1684.   else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious
  1685. event :-)
  1686.     wait( hevBlockLock,INFINITE );
  1687.     nWaitersBlocked -= nWaitersGone;        // something is going on here -
  1688. test of timeouts? :-)
  1689.     set_event( hevBlockLock );
  1690.     nWaitersGone = 0;
  1691.   }
  1692.   unlock( mtxUnblockLock );
  1693.   if ( 1 == nSignalsWasLeft ) {
  1694.     if ( 0 != eWasBroadcast ) {
  1695.       reset_event( hevBlockQueueB );
  1696.     }
  1697.     if ( 0 != nWaitersWasGone ) {
  1698.       reset_event( hevBlockQueueS );        // better now than spurious
  1699. later
  1700.     }
  1701.     set_event( hevBlockLock );              // open the gate
  1702.   }
  1703.   else if ( 0 != nSignalsWasLeft ) {
  1704.     set_event( hevBlockQueueS );            // unblock next waiter
  1705.   }
  1706.   lock( mtxExternal );
  1707.   return ( bTimedOut ) ? ETIMEOUT : 0;
  1708. }
  1709. signal(bAll) {
  1710.   [auto: register int    result        ]
  1711.   [auto: register HANDLE hevBlockQueue ]
  1712.   lock( mtxUnblockLock );
  1713.   if ( 0 != nWaitersToUnblock ) { // the gate is closed!!!
  1714.     if ( 0 == nWaitersBlocked ) { // NO-OP
  1715.       return unlock( mtxUnblockLock );
  1716.     }
  1717.     if (bAll) {
  1718.       nWaitersToUnblock += nWaitersBlocked;
  1719.       nWaitersBlocked = 0;
  1720.       eBroadcast = 2;
  1721.       hevBlockQueue = hevBlockQueueB;
  1722.     }
  1723.     else {
  1724.       nWaitersToUnblock++;
  1725.       nWaitersBlocked--;
  1726.       return unlock( mtxUnblockLock );
  1727.     }
  1728.   }
  1729.   else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION!
  1730.     wait( hevBlockLock,INFINITE ); // close the gate
  1731.     if ( 0 != nWaitersGone ) {
  1732.       nWaitersBlocked -= nWaitersGone;
  1733.       nWaitersGone = 0;
  1734.     }
  1735.     if (bAll) {
  1736.       nWaitersToUnblock = nWaitersBlocked;
  1737.       nWaitersBlocked = 0;
  1738.       eBroadcast = 1;
  1739.       hevBlockQueue = hevBlockQueueB;
  1740.     }
  1741.     else {
  1742.       nWaitersToUnblock = 1;
  1743.       nWaitersBlocked--;
  1744.       hevBlockQueue = hevBlockQueueS;
  1745.     }
  1746.   }
  1747.   else { // NO-OP
  1748.     return unlock( mtxUnblockLock );
  1749.   }
  1750.   unlock( mtxUnblockLock );
  1751.   set_event( hevBlockQueue );
  1752.   return result;
  1753. }
  1754. ---------------------- Forwarded by Alexander Terekhov/Germany/IBM on
  1755. 02/21/2001 09:13 AM ---------------------------
  1756. Alexander Terekhov
  1757. 02/20/2001 04:33 PM
  1758. To:   Louis Thomas <lthomas@arbitrade.com>
  1759. cc:
  1760. From: Alexander Terekhov/Germany/IBM@IBMDE
  1761. Subject:  RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio
  1762.       n questions
  1763. Importance:    Normal
  1764. >Sorry, gotta take a break and work on something else for a while.
  1765. >Real work
  1766. >calls, unfortunately. I'll get back to you in two or three days.
  1767. ok. no problem. here is some more stuff for pauses you might have
  1768. in between :)
  1769. ---------- Algorithm 7d / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ALL ------
  1770. given:
  1771. hevBlockLock - auto-reset event
  1772. hevBlockQueueS - auto-reset event  // for signals
  1773. hevBlockQueueB - manual-reset even // for broadcasts
  1774. mtxExternal - mutex or CS
  1775. mtxUnblockLock - mutex or CS
  1776. bBroadcast - int
  1777. nWaitersGone - int
  1778. nWaitersBlocked - int
  1779. nWaitersToUnblock - int
  1780. wait( timeout ) {
  1781.   [auto: register int result          ]     // error checking omitted
  1782.   [auto: register int bWasBroadcast   ]
  1783.   [auto: register int nSignalsWasLeft ]
  1784.   wait( hevBlockLock,INFINITE );
  1785.   nWaitersBlocked++;
  1786.   set_event( hevBlockLock );
  1787.   unlock( mtxExternal );
  1788.   bTimedOut = waitformultiple( hevBlockQueueS,hevBlockQueueB,timeout,ONE );
  1789.   lock( mtxUnblockLock );
  1790.   if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) {
  1791.     if ( bTimeout ) {                       // timeout (or canceled)
  1792.       if ( 0 != nWaitersBlocked ) {
  1793.         nWaitersBlocked--;
  1794.         nSignalsWasLeft = 0;                // do not unblock next waiter
  1795. below (already unblocked)
  1796.       }
  1797.       else if ( !bBroadcast ) {
  1798.         wait( hevBlockQueueS,INFINITE );    // better now than spurious
  1799. later
  1800.       }
  1801.     }
  1802.     if ( 0 == --nWaitersToUnblock ) {
  1803.       if ( 0 != nWaitersBlocked ) {
  1804.         if ( bBroadcast ) {
  1805.           reset_event( hevBlockQueueB );
  1806.           bBroadcast = false;
  1807.         }
  1808.         set_event( hevBlockLock );           // open the gate
  1809.         nSignalsWasLeft = 0;                 // do not open the gate below
  1810. again
  1811.       }
  1812.       else if ( false != (bWasBroadcast = bBroadcast) ) {
  1813.         bBroadcast = false;
  1814.       }
  1815.     }
  1816.     else {
  1817.       bWasBroadcast = bBroadcast;
  1818.     }
  1819.   }
  1820.   else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious
  1821. event :-)
  1822.     wait( hevBlockLock,INFINITE );
  1823.     nWaitersBlocked -= nWaitersGone;        // something is going on here -
  1824. test of timeouts? :-)
  1825.     set_event( hevBlockLock );
  1826.     nWaitersGone = 0;
  1827.   }
  1828.   unlock( mtxUnblockLock );
  1829.   if ( 1 == nSignalsWasLeft ) {
  1830.     if ( bWasBroadcast ) {
  1831.       reset_event( hevBlockQueueB );
  1832.     }
  1833.     set_event( hevBlockLock );              // open the gate
  1834.   }
  1835.   else if ( 0 != nSignalsWasLeft && !bWasBroadcast ) {
  1836.     set_event( hevBlockQueueS );            // unblock next waiter
  1837.   }
  1838.   lock( mtxExternal );
  1839.   return ( bTimedOut ) ? ETIMEOUT : 0;
  1840. }
  1841. signal(bAll) {
  1842.   [auto: register int    result        ]
  1843.   [auto: register HANDLE hevBlockQueue ]
  1844.   lock( mtxUnblockLock );
  1845.   if ( 0 != nWaitersToUnblock ) { // the gate is closed!!!
  1846.     if ( 0 == nWaitersBlocked ) { // NO-OP
  1847.       return unlock( mtxUnblockLock );
  1848.     }
  1849.     if (bAll) {
  1850.       nWaitersToUnblock += nWaitersBlocked;
  1851.       nWaitersBlocked = 0;
  1852.       bBroadcast = true;
  1853.       hevBlockQueue = hevBlockQueueB;
  1854.     }
  1855.     else {
  1856.       nWaitersToUnblock++;
  1857.       nWaitersBlocked--;
  1858.       return unlock( mtxUnblockLock );
  1859.     }
  1860.   }
  1861.   else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION!
  1862.     wait( hevBlockLock,INFINITE ); // close the gate
  1863.     if ( 0 != nWaitersGone ) {
  1864.       nWaitersBlocked -= nWaitersGone;
  1865.       nWaitersGone = 0;
  1866.     }
  1867.     if (bAll) {
  1868.       nWaitersToUnblock = nWaitersBlocked;
  1869.       nWaitersBlocked = 0;
  1870.       bBroadcast = true;
  1871.       hevBlockQueue = hevBlockQueueB;
  1872.     }
  1873.     else {
  1874.       nWaitersToUnblock = 1;
  1875.       nWaitersBlocked--;
  1876.       hevBlockQueue = hevBlockQueueS;
  1877.     }
  1878.   }
  1879.   else { // NO-OP
  1880.     return unlock( mtxUnblockLock );
  1881.   }
  1882.   unlock( mtxUnblockLock );
  1883.   set_event( hevBlockQueue );
  1884.   return result;
  1885. }
  1886. ----------------------------------------------------------------------------
  1887. Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio
  1888.      n questions
  1889. Date: Mon, 26 Feb 2001 22:20:12 -0600
  1890. From: Louis Thomas <lthomas@arbitrade.com>
  1891. To: "'TEREKHOV@de.ibm.com'" <TEREKHOV@de.ibm.com>
  1892. CC: rpj@ise.canberra.edu.au, Thomas Pfaff <tpfaff@gmx.net>,
  1893.      Nanbor Wang
  1894.      <nanbor@cs.wustl.edu>
  1895. Sorry all. Busy week.
  1896. > this insures the fairness
  1897. > which POSIX does not (e.g. two subsequent broadcasts - the gate does
  1898. insure
  1899. > that first wave waiters will start the race for the mutex before waiters
  1900. > from the second wave - Linux pthreads process/unblock both waves
  1901. > concurrently...)
  1902. I'm not sure how we are any more fair about this than Linux. We certainly
  1903. don't guarantee that the threads released by the first broadcast will get
  1904. the external mutex before the threads of the second wave. In fact, it is
  1905. possible that those threads will never get the external mutex if there is
  1906. enough contention for it.
  1907. > e.g. i was thinking about implementation with a pool of
  1908. > N semaphores/counters [...]
  1909. I considered that too. The problem is as you mentioned in a). You really
  1910. need to assign threads to semaphores once you know how you want to wake them
  1911. up, not when they first begin waiting which is the only time you can assign
  1912. them.
  1913. > well, i am not quite sure that i've fully understood your scenario,
  1914. Hmm. Well, it think it's an important example, so I'll try again. First, we
  1915. have thread A which we KNOW is waiting on a condition. As soon as it becomes
  1916. unblocked for any reason, we will know because it will set a flag. Since the
  1917. flag is not set, we are 100% confident that thread A is waiting on the
  1918. condition. We have another thread, thread B, which has acquired the mutex
  1919. and is about to wait on the condition. Thus it is pretty clear that at any
  1920. point, either just A is waiting, or A and B are waiting. Now thread C comes
  1921. along. C is about to do a broadcast on the condition. A broadcast is
  1922. guaranteed to unblock all threads currently waiting on a condition, right?
  1923. Again, we said that either just A is waiting, or A and B are both waiting.
  1924. So, when C does its broadcast, depending upon whether B has started waiting
  1925. or not, thread C will unblock A or unblock A and B. Either way, C must
  1926. unblock A, right?
  1927. Now, you said anything that happens is correct so long as a) "a signal is
  1928. not lost between unlocking the mutex and waiting on the condition" and b) "a
  1929. thread must not steal a signal it sent", correct? Requirement b) is easy to
  1930. satisfy: in this scenario, thread C will never wait on the condition, so it
  1931. won't steal any signals.  Requirement a) is not hard either. The only way we
  1932. could fail to meet requirement a) in this scenario is if thread B was
  1933. started waiting but didn't wake up because a signal was lost. This will not
  1934. happen.
  1935. Now, here is what happens. Assume thread C beats thread B. Thread C looks to
  1936. see how many threads are waiting on the condition. Thread C sees just one
  1937. thread, thread A, waiting. It does a broadcast waking up just one thread
  1938. because just one thread is waiting. Next, before A can become unblocked,
  1939. thread B begins waiting. Now there are two threads waiting, but only one
  1940. will be unblocked. Suppose B wins. B will become unblocked. A will not
  1941. become unblocked, because C only unblocked one thread (sema_post cond, 1).
  1942. So at the end, B finishes and A remains blocked.
  1943. We have met both of your requirements, so by your rules, this is an
  1944. acceptable outcome. However, I think that the spec says this is an
  1945. unacceptable outcome! We know for certain that A was waiting and that C did
  1946. a broadcast, but A did not become unblocked! Yet, the spec says that a
  1947. broadcast wakes up all waiting threads. This did not happen. Do you agree
  1948. that this shows your rules are not strict enough?
  1949. > and what about N2? :) this one does allow almost everything.
  1950. Don't get me started about rule #2. I'll NEVER advocate an algorithm that
  1951. uses rule 2 as an excuse to suck!
  1952. > but it is done (decrement)under mutex protection - this is not a subject
  1953. > of a race condition.
  1954. You are correct. My mistake.
  1955. > i would remove "_bTimedOut=false".. after all, it was a real timeout..
  1956. I disagree. A thread that can't successfully retract its waiter status can't
  1957. really have timed out. If a thread can't return without executing extra code
  1958. to deal with the fact that someone tried to unblock it, I think it is a poor
  1959. idea to pretend we
  1960. didn't realize someone was trying to signal us. After all, a signal is more
  1961. important than a time out.
  1962. > when nSignaled != 0, it is possible to update nWaiters (--) and do not
  1963. > touch nGone
  1964. I realize this, but I was thinking that writing it the other ways saves
  1965. another if statement.
  1966. > adjust only if nGone != 0 and save one cache memory write - probably much
  1967. slower than 'if'
  1968. Hmm. You are probably right.
  1969. > well, in a strange (e.g. timeout test) program you may (theoretically)
  1970. > have an overflow of nWaiters/nGone counters (with waiters repeatedly
  1971. timing
  1972. > out and no signals at all).
  1973. Also true. Not only that, but you also have the possibility that one could
  1974. overflow the number of waiters as well! However, considering the limit you
  1975. have chosen for nWaitersGone, I suppose it is unlikely that anyone would be
  1976. able to get INT_MAX/2 threads waiting on a single condition. :)
  1977. Analysis of 8a:
  1978. It looks correct to me.
  1979. What are IPC semaphores?
  1980. In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) {
  1981. // HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone
  1982. because nWaitersGone is never modified without holding mtxUnblockLock. You
  1983. are correct that there is a harmless race on nWaitersBlocked, which can
  1984. increase and make the condition become true just after we check it. If this
  1985. happens, we interpret it as the wait starting after the signal.
  1986. I like your optimization of this. You could improve Alg. 6 as follows:
  1987. ---------- Algorithm 6b ----------
  1988. signal(bAll) {
  1989.   _nSig=0
  1990.   lock counters
  1991.   // this is safe because nWaiting can only be decremented by a thread that
  1992.   // owns counters and nGone can only be changed by a thread that owns
  1993. counters.
  1994.   if (nWaiting>nGone) {
  1995.     if (0==nSignaled) {
  1996.       sema_wait gate // close gate if not already closed
  1997.     }
  1998.     if (nGone>0) {
  1999.       nWaiting-=nGone
  2000.       nGone=0
  2001.     }
  2002.     _nSig=bAll?nWaiting:1
  2003.     nSignaled+=_nSig
  2004.     nWaiting-=_nSig
  2005.   }
  2006.   unlock counters
  2007.   if (0!=_nSig) {
  2008.     sema_post queue, _nSig
  2009.   }
  2010. }
  2011. ---------- ---------- ----------
  2012. I guess this wouldn't apply to Alg 8a because nWaitersGone changes meanings
  2013. depending upon whether the gate is open or closed.
  2014. In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on
  2015. semBlockLock. Perhaps waiting on semBlockQueue would be a better idea.
  2016. What have you gained by making the last thread to be signaled do the waits
  2017. for all the timed out threads, besides added complexity? It took me a long
  2018. time to figure out what your objective was with this, to realize you were
  2019. using nWaitersGone to mean two different things, and to verify that you
  2020. hadn't introduced any bug by doing this. Even now I'm not 100% sure.
  2021. What has all this playing about with nWaitersGone really gained us besides a
  2022. lot of complexity (it is much harder to verify that this solution is
  2023. correct), execution overhead (we now have a lot more if statements to
  2024. evaluate), and space overhead (more space for the extra code, and another
  2025. integer in our data)? We did manage to save a lock/unlock pair in an
  2026. uncommon case (when a time out occurs) at the above mentioned expenses in
  2027. the common cases.
  2028. As for 8b, c, and d, they look ok though I haven't studied them thoroughly.
  2029. What would you use them for?
  2030.     Later,
  2031.         -Louis! :)
  2032. -----------------------------------------------------------------------------
  2033. Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio
  2034.      n questions
  2035. Date: Tue, 27 Feb 2001 15:51:28 +0100
  2036. From: TEREKHOV@de.ibm.com
  2037. To: Louis Thomas <lthomas@arbitrade.com>
  2038. CC: rpj@ise.canberra.edu.au, Thomas Pfaff <tpfaff@gmx.net>,
  2039.      Nanbor Wang <nanbor@cs.wustl.edu>
  2040. Hi Louis,
  2041. >> that first wave waiters will start the race for the mutex before waiters
  2042. >> from the second wave - Linux pthreads process/unblock both waves
  2043. >> concurrently...)
  2044. >
  2045. >I'm not sure how we are any more fair about this than Linux. We certainly
  2046. >don't guarantee that the threads released by the first broadcast will get
  2047. >the external mutex before the threads of the second wave. In fact, it is
  2048. >possible that those threads will never get the external mutex if there is
  2049. >enough contention for it.
  2050. correct. but gate is nevertheless more fair than Linux because of the
  2051. barrier it establishes between two races (1st and 2nd wave waiters) for
  2052. the mutex which under 'normal' circumstances (e.g. all threads of equal
  2053. priorities,..) will 'probably' result in fair behaviour with respect to
  2054. mutex ownership.
  2055. >> well, i am not quite sure that i've fully understood your scenario,
  2056. >
  2057. >Hmm. Well, it think it's an important example, so I'll try again. ...
  2058. ok. now i seem to understand this example. well, now it seems to me
  2059. that the only meaningful rule is just:
  2060. a) "a signal is not lost between unlocking the mutex and waiting on the
  2061. condition"
  2062. and that the rule
  2063. b) "a thread must not steal a signal it sent"
  2064. is not needed at all because a thread which violates b) also violates a).
  2065. i'll try to explain..
  2066. i think that the most important thing is how POSIX defines waiter's
  2067. visibility:
  2068. "if another thread is able to acquire the mutex after the about-to-block
  2069. thread
  2070. has released it, then a subsequent call to pthread_cond_signal() or
  2071. pthread_cond_broadcast() in that thread behaves as if it were issued after
  2072. the about-to-block thread has blocked. "
  2073. my understanding is the following:
  2074. 1) there is no guarantees whatsoever with respect to whether
  2075. signal/broadcast
  2076. will actually unblock any 'waiter' if it is done w/o acquiring the mutex
  2077. first
  2078. (note that a thread may release it before signal/broadcast - it does not
  2079. matter).
  2080. 2) it is guaranteed that waiters become 'visible' - eligible for unblock as
  2081. soon
  2082. as signalling thread acquires the mutex (but not before!!)
  2083. so..
  2084. >So, when C does its broadcast, depending upon whether B has started
  2085. waiting
  2086. >or not, thread C will unblock A or unblock A and B. Either way, C must
  2087. >unblock A, right?
  2088. right. but only if C did acquire the mutex prior to broadcast (it may
  2089. release it before broadcast as well).
  2090. implementation will violate waiters visibility rule (signal will become
  2091. lost)
  2092. if C will not unblock A.
  2093. >Now, here is what happens. Assume thread C beats thread B. Thread C looks
  2094. to
  2095. >see how many threads are waiting on the condition. Thread C sees just one
  2096. >thread, thread A, waiting. It does a broadcast waking up just one thread
  2097. >because just one thread is waiting. Next, before A can become unblocked,
  2098. >thread B begins waiting. Now there are two threads waiting, but only one
  2099. >will be unblocked. Suppose B wins. B will become unblocked. A will not
  2100. >become unblocked, because C only unblocked one thread (sema_post cond, 1).
  2101. >So at the end, B finishes and A remains blocked.
  2102. thread C did acquire the mutex ("Thread C sees just one thread, thread A,
  2103. waiting"). beginning from that moment it is guaranteed that subsequent
  2104. broadcast will unblock A. Otherwise we will have a lost signal with respect
  2105. to A. I do think that it does not matter whether the signal was physically
  2106. (completely) lost or was just stolen by another thread (B) - in both cases
  2107. it was simply lost with respect to A.
  2108. >..Do you agree that this shows your rules are not strict enough?
  2109. probably the opposite.. :-) i think that it shows that the only meaningful
  2110. rule is
  2111. a) "a signal is not lost between unlocking the mutex and waiting on the
  2112. condition"
  2113. with clarification of waiters visibility as defined by POSIX above.
  2114. >> i would remove "_bTimedOut=false".. after all, it was a real timeout..
  2115. >
  2116. >I disagree. A thread that can't successfully retract its waiter status
  2117. can't
  2118. >really have timed out. If a thread can't return without executing extra
  2119. code
  2120. >to deal with the fact that someone tried to unblock it, I think it is a
  2121. poor
  2122. >idea to pretend we
  2123. >didn't realize someone was trying to signal us. After all, a signal is
  2124. more
  2125. >important than a time out.
  2126. a) POSIX does allow timed out thread to consume a signal (cancelled is
  2127. not).
  2128. b) ETIMEDOUT status just says that: "The time specified by abstime to
  2129. pthread_cond_timedwait() has passed."
  2130. c) it seem to me that hiding timeouts would violate "The
  2131. pthread_cond_timedwait()
  2132. function is the same as pthread_cond_wait() except that an error is
  2133. returned if
  2134. the absolute time specified by abstime passes (that is, system time equals
  2135. or
  2136. exceeds abstime) before the condition cond is signaled or broadcasted"
  2137. because
  2138. the abs. time did really pass before cond was signaled (waiter was
  2139. released via semaphore). however, if it really matters, i could imaging
  2140. that we
  2141. can save an abs. time of signal/broadcast and compare it with timeout after
  2142. unblock to find out whether it was a 'real' timeout or not. absent this
  2143. check
  2144. i do think that hiding timeouts would result in technical violation of
  2145. specification.. but i think that this check is not important and we can
  2146. simply
  2147. trust timeout error code provided by wait since we are not trying to make
  2148. 'hard' realtime implementation.
  2149. >What are IPC semaphores?
  2150. <sys/sem.h>
  2151. int   semctl(int, int, int, ...);
  2152. int   semget(key_t, int, int);
  2153. int   semop(int, struct sembuf *, size_t);
  2154. they support adjustment of semaphore counter (semvalue)
  2155. in one single call - imaging Win32 ReleaseSemaphore( hsem,-N )
  2156. >In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) {
  2157. >// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone
  2158. >because nWaitersGone is never modified without holding mtxUnblockLock. You
  2159. >are correct that there is a harmless race on nWaitersBlocked, which can
  2160. >increase and make the condition become true just after we check it. If
  2161. this
  2162. >happens, we interpret it as the wait starting after the signal.
  2163. well, the reason why i've asked on comp.programming.threads whether this
  2164. race
  2165. condition is harmless or not is that in order to be harmless it should not
  2166. violate the waiters visibility rule (see above). Fortunately, we increment
  2167. the counter under protection of external mutex.. so that any (signalling)
  2168. thread which will acquire the mutex next, should see the updated counter
  2169. (in signal) according to POSIX memory visibility rules and mutexes
  2170. (memory barriers). But i am not so sure how it actually works on
  2171. Win32/INTEL
  2172. which does not explicitly define any memory visibility rules :(
  2173. >I like your optimization of this. You could improve Alg. 6 as follows:
  2174. >---------- Algorithm 6b ----------
  2175. >signal(bAll) {
  2176. >  _nSig=0
  2177. >  lock counters
  2178. >  // this is safe because nWaiting can only be decremented by a thread
  2179. that
  2180. >  // owns counters and nGone can only be changed by a thread that owns
  2181. >counters.
  2182. >  if (nWaiting>nGone) {
  2183. >    if (0==nSignaled) {
  2184. >      sema_wait gate // close gate if not already closed
  2185. >    }
  2186. >    if (nGone>0) {
  2187. >      nWaiting-=nGone
  2188. >      nGone=0
  2189. >    }
  2190. >    _nSig=bAll?nWaiting:1
  2191. >    nSignaled+=_nSig
  2192. >    nWaiting-=_nSig
  2193. >  }
  2194. >  unlock counters
  2195. >  if (0!=_nSig) {
  2196. >    sema_post queue, _nSig
  2197. >  }
  2198. >}
  2199. >---------- ---------- ----------
  2200. >I guess this wouldn't apply to Alg 8a because nWaitersGone changes
  2201. meanings
  2202. >depending upon whether the gate is open or closed.
  2203. agree.
  2204. >In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on
  2205. >semBlockLock. Perhaps waiting on semBlockQueue would be a better idea.
  2206. you are correct. my mistake.
  2207. >What have you gained by making the last thread to be signaled do the waits
  2208. >for all the timed out threads, besides added complexity? It took me a long
  2209. >time to figure out what your objective was with this, to realize you were
  2210. >using nWaitersGone to mean two different things, and to verify that you
  2211. >hadn't introduced any bug by doing this. Even now I'm not 100% sure.
  2212. >
  2213. >What has all this playing about with nWaitersGone really gained us besides
  2214. a
  2215. >lot of complexity (it is much harder to verify that this solution is
  2216. >correct), execution overhead (we now have a lot more if statements to
  2217. >evaluate), and space overhead (more space for the extra code, and another
  2218. >integer in our data)? We did manage to save a lock/unlock pair in an
  2219. >uncommon case (when a time out occurs) at the above mentioned expenses in
  2220. >the common cases.
  2221. well, please consider the following:
  2222. 1) with multiple waiters unblocked (but some timed out) the trick with
  2223. counter
  2224. seem to ensure potentially higher level of concurrency by not delaying
  2225. most of unblocked waiters for semaphore cleanup - only the last one
  2226. will be delayed but all others would already contend/acquire/release
  2227. the external mutex - the critical section protected by mtxUnblockLock is
  2228. made smaller (increment + couple of IFs is faster than system/kernel call)
  2229. which i think is good in general. however, you are right, this is done
  2230. at expense of 'normal' waiters..
  2231. 2) some semaphore APIs (e.g. POSIX IPC sems) do allow to adjust the
  2232. semaphore counter in one call => less system/kernel calls.. imagine:
  2233. if ( 1 == nSignalsWasLeft ) {
  2234.     if ( 0 != nWaitersWasGone ) {
  2235.       ReleaseSemaphore( semBlockQueue,-nWaitersWasGone );  // better now
  2236. than spurious later
  2237.     }
  2238.     sem_post( semBlockLock );              // open the gate
  2239.   }
  2240. 3) even on win32 a single thread doing multiple cleanup calls (to wait)
  2241. will probably result in faster execution (because of processor caching)
  2242. than multiple threads each doing a single call to wait.
  2243. >As for 8b, c, and d, they look ok though I haven't studied them
  2244. thoroughly.
  2245. >What would you use them for?
  2246. 8b) for semaphores which do not allow to unblock multiple waiters
  2247. in a single call to post/release (e.g. POSIX realtime semaphores -
  2248. <semaphore.h>)
  2249. 8c/8d) for WinCE prior to 3.0 (WinCE 3.0 does have semaphores)
  2250. ok. so, which one is the 'final' algorithm(s) which we should use in
  2251. pthreads-win32??
  2252. regards,
  2253. alexander.
  2254. ----------------------------------------------------------------------------
  2255. Louis Thomas <lthomas@arbitrade.com> on 02/27/2001 05:20:12 AM
  2256. Please respond to Louis Thomas <lthomas@arbitrade.com>
  2257. To:   Alexander Terekhov/Germany/IBM@IBMDE
  2258. cc:   rpj@ise.canberra.edu.au, Thomas Pfaff <tpfaff@gmx.net>, Nanbor Wang
  2259.       <nanbor@cs.wustl.edu>
  2260. Subject:  RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio
  2261.       n questions
  2262. Sorry all. Busy week.
  2263. > this insures the fairness
  2264. > which POSIX does not (e.g. two subsequent broadcasts - the gate does
  2265. insure
  2266. > that first wave waiters will start the race for the mutex before waiters
  2267. > from the second wave - Linux pthreads process/unblock both waves
  2268. > concurrently...)
  2269. I'm not sure how we are any more fair about this than Linux. We certainly
  2270. don't guarantee that the threads released by the first broadcast will get
  2271. the external mutex before the threads of the second wave. In fact, it is
  2272. possible that those threads will never get the external mutex if there is
  2273. enough contention for it.
  2274. > e.g. i was thinking about implementation with a pool of
  2275. > N semaphores/counters [...]
  2276. I considered that too. The problem is as you mentioned in a). You really
  2277. need to assign threads to semaphores once you know how you want to wake
  2278. them
  2279. up, not when they first begin waiting which is the only time you can assign
  2280. them.
  2281. > well, i am not quite sure that i've fully understood your scenario,
  2282. Hmm. Well, it think it's an important example, so I'll try again. First, we
  2283. have thread A which we KNOW is waiting on a condition. As soon as it
  2284. becomes
  2285. unblocked for any reason, we will know because it will set a flag. Since
  2286. the
  2287. flag is not set, we are 100% confident that thread A is waiting on the
  2288. condition. We have another thread, thread B, which has acquired the mutex
  2289. and is about to wait on the condition. Thus it is pretty clear that at any
  2290. point, either just A is waiting, or A and B are waiting. Now thread C comes
  2291. along. C is about to do a broadcast on the condition. A broadcast is
  2292. guaranteed to unblock all threads currently waiting on a condition, right?
  2293. Again, we said that either just A is waiting, or A and B are both waiting.
  2294. So, when C does its broadcast, depending upon whether B has started waiting
  2295. or not, thread C will unblock A or unblock A and B. Either way, C must
  2296. unblock A, right?
  2297. Now, you said anything that happens is correct so long as a) "a signal is
  2298. not lost between unlocking the mutex and waiting on the condition" and b)
  2299. "a
  2300. thread must not steal a signal it sent", correct? Requirement b) is easy to
  2301. satisfy: in this scenario, thread C will never wait on the condition, so it
  2302. won't steal any signals.  Requirement a) is not hard either. The only way
  2303. we
  2304. could fail to meet requirement a) in this scenario is if thread B was
  2305. started waiting but didn't wake up because a signal was lost. This will not
  2306. happen.
  2307. Now, here is what happens. Assume thread C beats thread B. Thread C looks
  2308. to
  2309. see how many threads are waiting on the condition. Thread C sees just one
  2310. thread, thread A, waiting. It does a broadcast waking up just one thread
  2311. because just one thread is waiting. Next, before A can become unblocked,
  2312. thread B begins waiting. Now there are two threads waiting, but only one
  2313. will be unblocked. Suppose B wins. B will become unblocked. A will not
  2314. become unblocked, because C only unblocked one thread (sema_post cond, 1).
  2315. So at the end, B finishes and A remains blocked.
  2316. We have met both of your requirements, so by your rules, this is an
  2317. acceptable outcome. However, I think that the spec says this is an
  2318. unacceptable outcome! We know for certain that A was waiting and that C did
  2319. a broadcast, but A did not become unblocked! Yet, the spec says that a
  2320. broadcast wakes up all waiting threads. This did not happen. Do you agree
  2321. that this shows your rules are not strict enough?
  2322. > and what about N2? :) this one does allow almost everything.
  2323. Don't get me started about rule #2. I'll NEVER advocate an algorithm that
  2324. uses rule 2 as an excuse to suck!
  2325. > but it is done (decrement)under mutex protection - this is not a subject
  2326. > of a race condition.
  2327. You are correct. My mistake.
  2328. > i would remove "_bTimedOut=false".. after all, it was a real timeout..
  2329. I disagree. A thread that can't successfully retract its waiter status
  2330. can't
  2331. really have timed out. If a thread can't return without executing extra
  2332. code
  2333. to deal with the fact that someone tried to unblock it, I think it is a
  2334. poor
  2335. idea to pretend we
  2336. didn't realize someone was trying to signal us. After all, a signal is more
  2337. important than a time out.
  2338. > when nSignaled != 0, it is possible to update nWaiters (--) and do not
  2339. > touch nGone
  2340. I realize this, but I was thinking that writing it the other ways saves
  2341. another if statement.
  2342. > adjust only if nGone != 0 and save one cache memory write - probably much
  2343. slower than 'if'
  2344. Hmm. You are probably right.
  2345. > well, in a strange (e.g. timeout test) program you may (theoretically)
  2346. > have an overflow of nWaiters/nGone counters (with waiters repeatedly
  2347. timing
  2348. > out and no signals at all).
  2349. Also true. Not only that, but you also have the possibility that one could
  2350. overflow the number of waiters as well! However, considering the limit you
  2351. have chosen for nWaitersGone, I suppose it is unlikely that anyone would be
  2352. able to get INT_MAX/2 threads waiting on a single condition. :)
  2353. Analysis of 8a:
  2354. It looks correct to me.
  2355. What are IPC semaphores?
  2356. In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) {
  2357. // HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone
  2358. because nWaitersGone is never modified without holding mtxUnblockLock. You
  2359. are correct that there is a harmless race on nWaitersBlocked, which can
  2360. increase and make the condition become true just after we check it. If this
  2361. happens, we interpret it as the wait starting after the signal.
  2362. I like your optimization of this. You could improve Alg. 6 as follows:
  2363. ---------- Algorithm 6b ----------
  2364. signal(bAll) {
  2365.   _nSig=0
  2366.   lock counters
  2367.   // this is safe because nWaiting can only be decremented by a thread that
  2368.   // owns counters and nGone can only be changed by a thread that owns
  2369. counters.
  2370.   if (nWaiting>nGone) {
  2371.     if (0==nSignaled) {
  2372.       sema_wait gate // close gate if not already closed
  2373.     }
  2374.     if (nGone>0) {
  2375.       nWaiting-=nGone
  2376.       nGone=0
  2377.     }
  2378.     _nSig=bAll?nWaiting:1
  2379.     nSignaled+=_nSig
  2380.     nWaiting-=_nSig
  2381.   }
  2382.   unlock counters
  2383.   if (0!=_nSig) {
  2384.     sema_post queue, _nSig
  2385.   }
  2386. }
  2387. ---------- ---------- ----------
  2388. I guess this wouldn't apply to Alg 8a because nWaitersGone changes meanings
  2389. depending upon whether the gate is open or closed.
  2390. In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on
  2391. semBlockLock. Perhaps waiting on semBlockQueue would be a better idea.
  2392. What have you gained by making the last thread to be signaled do the waits
  2393. for all the timed out threads, besides added complexity? It took me a long
  2394. time to figure out what your objective was with this, to realize you were
  2395. using nWaitersGone to mean two different things, and to verify that you
  2396. hadn't introduced any bug by doing this. Even now I'm not 100% sure.
  2397. What has all this playing about with nWaitersGone really gained us besides
  2398. a
  2399. lot of complexity (it is much harder to verify that this solution is
  2400. correct), execution overhead (we now have a lot more if statements to
  2401. evaluate), and space overhead (more space for the extra code, and another
  2402. integer in our data)? We did manage to save a lock/unlock pair in an
  2403. uncommon case (when a time out occurs) at the above mentioned expenses in
  2404. the common cases.
  2405. As for 8b, c, and d, they look ok though I haven't studied them thoroughly.
  2406. What would you use them for?
  2407.     Later,
  2408.         -Louis! :)