fork(1) download
  1. // Copyright 2016 <Biagio Festa>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <string>
  6. #include <thread>
  7. #include <cstring>
  8. #include <cassert>
  9.  
  10. void reverse_str_mt(char* str,
  11. const size_t len,
  12. const size_t id_thread,
  13. const size_t max_num_threads) {
  14. // Some assertion on input parameters
  15. assert(str != nullptr);
  16. assert(max_num_threads != 0);
  17.  
  18. // In case the num of threads is greater than the len of the string
  19. if (id_thread > len) {
  20. assert(max_num_threads > len);
  21. return;
  22. }
  23.  
  24. // Swap operation
  25. for (size_t i = id_thread; i <= len / 2; i += max_num_threads) {
  26. std::swap(str[i], str[len - i - 1]);
  27. }
  28. }
  29.  
  30. int main(int argc, char *argv[]) {
  31. static constexpr size_t NUM_THREADS = 10;
  32. char str[] = "123456";
  33. const auto len = strlen(str);
  34.  
  35. std::vector<std::thread> threads;
  36. for (size_t i = 0; i < NUM_THREADS; ++i) {
  37. threads.emplace_back(reverse_str_mt, str, len , i, NUM_THREADS);
  38. }
  39.  
  40. // Join threads
  41. for (auto& t : threads) {
  42. t.join();
  43. }
  44.  
  45. std::cout << str << std::endl;
  46. return 0;
  47. }
  48.  
  49.  
Success #stdin #stdout 0s 44424KB
stdin
Standard input is empty
stdout
653421