You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

287 lines
10 KiB

  1. /*
  2. Copyright 2005-2014 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks.
  4. Threading Building Blocks is free software; you can redistribute it
  5. and/or modify it under the terms of the GNU General Public License
  6. version 2 as published by the Free Software Foundation.
  7. Threading Building Blocks is distributed in the hope that it will be
  8. useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  9. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with Threading Building Blocks; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. As a special exception, you may use this file as part of a free software
  15. library without restriction. Specifically, if other files instantiate
  16. templates or use macros or inline functions from this file, or you compile
  17. this file and link it with other files to produce an executable, this
  18. file does not by itself cause the resulting executable to be covered by
  19. the GNU General Public License. This exception does not however
  20. invalidate any other reasons why the executable file might be covered by
  21. the GNU General Public License.
  22. */
  23. //
  24. // Example program that reads a file of decimal integers in text format
  25. // and changes each to its square.
  26. //
  27. #include "tbb/pipeline.h"
  28. #include "tbb/tick_count.h"
  29. #include "tbb/task_scheduler_init.h"
  30. #include "tbb/tbb_allocator.h"
  31. #include <cstring>
  32. #include <cstdlib>
  33. #include <cstdio>
  34. #include <cctype>
  35. #include "../../common/utility/utility.h"
  36. extern void generate_if_needed(const char*);
  37. using namespace std;
  38. //! Holds a slice of text.
  39. /** Instances *must* be allocated/freed using methods herein, because the C++ declaration
  40. represents only the header of a much larger object in memory. */
  41. class TextSlice {
  42. //! Pointer to one past last character in sequence
  43. char* logical_end;
  44. //! Pointer to one past last available byte in sequence.
  45. char* physical_end;
  46. public:
  47. //! Allocate a TextSlice object that can hold up to max_size characters.
  48. static TextSlice* allocate( size_t max_size ) {
  49. // +1 leaves room for a terminating null character.
  50. TextSlice* t = (TextSlice*)tbb::tbb_allocator<char>().allocate( sizeof(TextSlice)+max_size+1 );
  51. t->logical_end = t->begin();
  52. t->physical_end = t->begin()+max_size;
  53. return t;
  54. }
  55. //! Free a TextSlice object
  56. void free() {
  57. tbb::tbb_allocator<char>().deallocate((char*)this,sizeof(TextSlice)+(physical_end-begin())+1);
  58. }
  59. //! Pointer to beginning of sequence
  60. char* begin() {return (char*)(this+1);}
  61. //! Pointer to one past last character in sequence
  62. char* end() {return logical_end;}
  63. //! Length of sequence
  64. size_t size() const {return logical_end-(char*)(this+1);}
  65. //! Maximum number of characters that can be appended to sequence
  66. size_t avail() const {return physical_end-logical_end;}
  67. //! Append sequence [first,last) to this sequence.
  68. void append( char* first, char* last ) {
  69. memcpy( logical_end, first, last-first );
  70. logical_end += last-first;
  71. }
  72. //! Set end() to given value.
  73. void set_end( char* p ) {logical_end=p;}
  74. };
  75. size_t MAX_CHAR_PER_INPUT_SLICE = 4000;
  76. string InputFileName = "input.txt";
  77. string OutputFileName = "output.txt";
  78. class MyInputFilter: public tbb::filter {
  79. public:
  80. MyInputFilter( FILE* input_file_ );
  81. ~MyInputFilter();
  82. private:
  83. FILE* input_file;
  84. TextSlice* next_slice;
  85. /*override*/ void* operator()(void*);
  86. };
  87. MyInputFilter::MyInputFilter( FILE* input_file_ ) :
  88. filter(serial_in_order),
  89. input_file(input_file_),
  90. next_slice( TextSlice::allocate( MAX_CHAR_PER_INPUT_SLICE ) )
  91. {
  92. }
  93. MyInputFilter::~MyInputFilter() {
  94. next_slice->free();
  95. }
  96. void* MyInputFilter::operator()(void*) {
  97. // Read characters into space that is available in the next slice.
  98. size_t m = next_slice->avail();
  99. size_t n = fread( next_slice->end(), 1, m, input_file );
  100. if( !n && next_slice->size()==0 ) {
  101. // No more characters to process
  102. return NULL;
  103. } else {
  104. // Have more characters to process.
  105. TextSlice& t = *next_slice;
  106. next_slice = TextSlice::allocate( MAX_CHAR_PER_INPUT_SLICE );
  107. char* p = t.end()+n;
  108. if( n==m ) {
  109. // Might have read partial number. If so, transfer characters of partial number to next slice.
  110. while( p>t.begin() && isdigit(p[-1]) )
  111. --p;
  112. next_slice->append( p, t.end()+n );
  113. }
  114. t.set_end(p);
  115. return &t;
  116. }
  117. }
  118. //! Filter that changes each decimal number to its square.
  119. class MyTransformFilter: public tbb::filter {
  120. public:
  121. MyTransformFilter();
  122. /*override*/void* operator()( void* item );
  123. };
  124. MyTransformFilter::MyTransformFilter() :
  125. tbb::filter(parallel)
  126. {}
  127. /*override*/void* MyTransformFilter::operator()( void* item ) {
  128. TextSlice& input = *static_cast<TextSlice*>(item);
  129. // Add terminating null so that strtol works right even if number is at end of the input.
  130. *input.end() = '\0';
  131. char* p = input.begin();
  132. TextSlice& out = *TextSlice::allocate( 2*MAX_CHAR_PER_INPUT_SLICE );
  133. char* q = out.begin();
  134. for(;;) {
  135. while( p<input.end() && !isdigit(*p) )
  136. *q++ = *p++;
  137. if( p==input.end() )
  138. break;
  139. long x = strtol( p, &p, 10 );
  140. // Note: no overflow checking is needed here, as we have twice the
  141. // input string length, but the square of a non-negative integer n
  142. // cannot have more than twice as many digits as n.
  143. long y = x*x;
  144. sprintf(q,"%ld",y);
  145. q = strchr(q,0);
  146. }
  147. out.set_end(q);
  148. input.free();
  149. return &out;
  150. }
  151. //! Filter that writes each buffer to a file.
  152. class MyOutputFilter: public tbb::filter {
  153. FILE* my_output_file;
  154. public:
  155. MyOutputFilter( FILE* output_file );
  156. /*override*/void* operator()( void* item );
  157. };
  158. MyOutputFilter::MyOutputFilter( FILE* output_file ) :
  159. tbb::filter(serial_in_order),
  160. my_output_file(output_file)
  161. {
  162. }
  163. void* MyOutputFilter::operator()( void* item ) {
  164. TextSlice& out = *static_cast<TextSlice*>(item);
  165. size_t n = fwrite( out.begin(), 1, out.size(), my_output_file );
  166. if( n!=out.size() ) {
  167. fprintf(stderr,"Can't write into file '%s'\n", OutputFileName.c_str());
  168. exit(1);
  169. }
  170. out.free();
  171. return NULL;
  172. }
  173. bool silent = false;
  174. int run_pipeline( int nthreads )
  175. {
  176. FILE* input_file = fopen( InputFileName.c_str(), "r" );
  177. if( !input_file ) {
  178. throw std::invalid_argument( ("Invalid input file name: "+InputFileName).c_str() );
  179. return 0;
  180. }
  181. FILE* output_file = fopen( OutputFileName.c_str(), "w" );
  182. if( !output_file ) {
  183. throw std::invalid_argument( ("Invalid output file name: "+OutputFileName).c_str() );
  184. return 0;
  185. }
  186. // Create the pipeline
  187. tbb::pipeline pipeline;
  188. // Create file-reading writing stage and add it to the pipeline
  189. MyInputFilter input_filter( input_file );
  190. pipeline.add_filter( input_filter );
  191. // Create squaring stage and add it to the pipeline
  192. MyTransformFilter transform_filter;
  193. pipeline.add_filter( transform_filter );
  194. // Create file-writing stage and add it to the pipeline
  195. MyOutputFilter output_filter( output_file );
  196. pipeline.add_filter( output_filter );
  197. // Run the pipeline
  198. tbb::tick_count t0 = tbb::tick_count::now();
  199. // Need more than one token in flight per thread to keep all threads
  200. // busy; 2-4 works
  201. pipeline.run( nthreads*4 );
  202. tbb::tick_count t1 = tbb::tick_count::now();
  203. fclose( output_file );
  204. fclose( input_file );
  205. if ( !silent ) printf("time = %g\n", (t1-t0).seconds());
  206. return 1;
  207. }
  208. int main( int argc, char* argv[] ) {
  209. try {
  210. tbb::tick_count mainStartTime = tbb::tick_count::now();
  211. // The 1st argument is the function to obtain 'auto' value; the 2nd is the default value
  212. // The example interprets 0 threads as "run serially, then fully subscribed"
  213. utility::thread_number_range threads( tbb::task_scheduler_init::default_num_threads, 0 );
  214. utility::parse_cli_arguments(argc,argv,
  215. utility::cli_argument_pack()
  216. //"-h" option for displaying help is present implicitly
  217. .positional_arg(threads,"n-of-threads",utility::thread_number_range_desc)
  218. .positional_arg(InputFileName,"input-file","input file name")
  219. .positional_arg(OutputFileName,"output-file","output file name")
  220. .positional_arg(MAX_CHAR_PER_INPUT_SLICE, "max-slice-size","the maximum number of characters in one slice")
  221. .arg(silent,"silent","no output except elapsed time")
  222. );
  223. generate_if_needed( InputFileName.c_str() );
  224. if ( threads.first ) {
  225. for(int p = threads.first; p <= threads.last; p=threads.step(p) ) {
  226. if ( !silent ) printf("threads = %d ", p);
  227. tbb::task_scheduler_init init(p);
  228. if(!run_pipeline (p))
  229. return 1;
  230. }
  231. } else { // Number of threads wasn't set explicitly. Run serial and parallel version
  232. { // serial run
  233. if ( !silent ) printf("serial run ");
  234. tbb::task_scheduler_init init_serial(1);
  235. if(!run_pipeline (1))
  236. return 1;
  237. }
  238. { // parallel run (number of threads is selected automatically)
  239. if ( !silent ) printf("parallel run ");
  240. tbb::task_scheduler_init init_parallel;
  241. if(!run_pipeline (init_parallel.default_num_threads()))
  242. return 1;
  243. }
  244. }
  245. utility::report_elapsed_time((tbb::tick_count::now() - mainStartTime).seconds());
  246. return 0;
  247. } catch(std::exception& e) {
  248. std::cerr<<"error occurred. error text is :\"" <<e.what()<<"\"\n";
  249. return 1;
  250. }
  251. }