skynet_pthread.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <algorithm>
  2. #include <cassert>
  3. #include <chrono>
  4. #include <cstddef>
  5. #include <cstdint>
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <memory>
  9. #include <numeric>
  10. #include <stdexcept>
  11. #include <vector>
  12. extern "C" {
  13. #include <pthread.h>
  14. #include <signal.h>
  15. }
  16. #include "buffered_channel.hpp"
  17. using channel_type = buffered_channel< std::uint64_t >;
  18. using clock_type = std::chrono::steady_clock;
  19. using duration_type = clock_type::duration;
  20. using time_point_type = clock_type::time_point;
  21. struct thread_args {
  22. channel_type & c;
  23. std::size_t num;
  24. std::size_t size;
  25. std::size_t div;
  26. };
  27. // microbenchmark
  28. void * skynet( void * vargs) {
  29. thread_args * args = static_cast< thread_args * >( vargs);
  30. if ( 1 == args->size) {
  31. args->c.push( args->num);
  32. } else {
  33. channel_type rc{ 16 };
  34. for ( std::size_t i = 0; i < args->div; ++i) {
  35. auto sub_num = args->num + i * args->size / args->div;
  36. auto sub_size = args->size / args->div;
  37. auto size = 8 * 1024;
  38. pthread_attr_t tattr;
  39. if ( 0 != ::pthread_attr_init( & tattr) ) {
  40. std::runtime_error("pthread_attr_init() failed");
  41. }
  42. if ( 0 != ::pthread_attr_setstacksize( & tattr, size) ) {
  43. std::runtime_error("pthread_attr_setstacksize() failed");
  44. }
  45. thread_args * targs = new thread_args{ rc, sub_num, sub_size, args->div };
  46. pthread_t tid;
  47. if ( 0 != ::pthread_create( & tid, & tattr, & skynet, targs) ) {
  48. std::runtime_error("pthread_create() failed");
  49. }
  50. if ( 0 != ::pthread_detach( tid) ) {
  51. std::runtime_error("pthread_detach() failed");
  52. }
  53. }
  54. std::uint64_t sum{ 0 };
  55. for ( std::size_t i = 0; i < args->div; ++i) {
  56. sum += rc.value_pop();
  57. }
  58. args->c.push( sum);
  59. }
  60. delete args;
  61. return nullptr;
  62. }
  63. int main() {
  64. try {
  65. std::size_t size{ 10000 };
  66. std::size_t div{ 10 };
  67. std::uint64_t result{ 0 };
  68. duration_type duration{ duration_type::zero() };
  69. channel_type rc{ 2 };
  70. thread_args * targs = new thread_args{ rc, 0, size, div };
  71. time_point_type start{ clock_type::now() };
  72. skynet( targs);
  73. result = rc.value_pop();
  74. duration = clock_type::now() - start;
  75. std::cout << "Result: " << result << " in " << duration.count() / 1000000 << " ms" << std::endl;
  76. std::cout << "done." << std::endl;
  77. return EXIT_SUCCESS;
  78. } catch ( std::exception const& e) {
  79. std::cerr << "exception: " << e.what() << std::endl;
  80. } catch (...) {
  81. std::cerr << "unhandled exception" << std::endl;
  82. }
  83. return EXIT_FAILURE;
  84. }