Guest User

Untitled

a guest
Jan 23rd, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. /****
  2. * Attempt to have fc::threads use fc::mutex when yield() causes a context switch
  3. */
  4. BOOST_AUTO_TEST_CASE( yield_with_mutex )
  5. {
  6. // set up thread pool
  7. uint16_t num_threads = 5;
  8. std::vector<fc::thread*> thread_collection;
  9. for(uint16_t i = 0; i < num_threads; i++)
  10. thread_collection.push_back(new fc::thread("My" + std::to_string(i)));
  11.  
  12. // the function that will give a thread something to do
  13. fc::mutex my_mutex;
  14. volatile uint32_t my_mutable = 0;
  15. auto my_func = ([&my_mutable, &my_mutex] ()
  16. {
  17. // grab the mutex
  18. my_mutex.lock();
  19. // get the prior value
  20. uint32_t old_value = my_mutable;
  21. // modify the value
  22. my_mutable++;
  23. // yield
  24. fc::yield();
  25. // test to see if the mutex is recursive
  26. my_mutex.lock();
  27. // return the value to the original
  28. my_mutable--;
  29. my_mutex.unlock();
  30. // verify the original still matches
  31. if (old_value != my_mutable)
  32. BOOST_FAIL("Values do not match");
  33. my_mutex.unlock();
  34. });
  35.  
  36. // the loop that gives threads the work
  37. uint16_t thread_counter = 0;
  38. uint32_t num_loops = 50000;
  39. std::vector<fc::future<void>> futures(num_loops);
  40. for(uint32_t i = 0; i < num_loops; ++i)
  41. {
  42. futures[i] = thread_collection[thread_counter]->async(my_func);
  43. ++thread_counter;
  44. if (thread_counter == num_threads)
  45. thread_counter = 0;
  46. }
  47.  
  48. // now wait for each to finish
  49. for(uint32_t i = 0; i < num_loops; ++i)
  50. futures[i].wait();
  51.  
  52. // clean up the thread pointers
  53. for(uint16_t i = 0; i < num_threads; i++)
  54. delete thread_collection[i];
  55.  
  56. // verify that evertying worked
  57. BOOST_CHECK_EQUAL(0u, my_mutable);
  58. }
Add Comment
Please, Sign In to add comment