Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. //
  2. //  main.mm
  3. //  dispatch_test
  4. //
  5. //  Created by Antony Searle on 20/9/19.
  6. //  Copyright © 2019 Antony Searle. All rights reserved.
  7. //
  8.  
  9. #import <Foundation/Foundation.h>
  10.  
  11. #include <atomic>
  12. #include <thread>
  13.  
  14. int main(int argc, const char * argv[]) {
  15.     // std::atomic<long> x(0);
  16.     auto N = 1000;
  17.     auto M = 100'000'000;
  18.     auto active = new std::atomic<long>(0);
  19.     auto barrier = new std::atomic<long>(N);
  20.     printf("concurrency %u\n", std::thread::hardware_concurrency());
  21.     auto q = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
  22.     @autoreleasepool {
  23.         for (long i = 0; i != N; ++i) {
  24.             // auto q = dispatch_queue_create(nullptr, DISPATCH_QUEUE_CONCURRENT);
  25.             // auto q = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL);
  26.             dispatch_async(q, ^{
  27.                 long z = active->fetch_add(1, std::memory_order_acq_rel);
  28.                 // std::this_thread::sleep_for(std::chrono::seconds(1));
  29.                 for (auto j = 0; j != M; ++j) // do some work
  30.                     z *= z;
  31.                 printf("%ld\t%ld/%ld\n", active->fetch_sub(1, std::memory_order_acq_rel), i, z);
  32.                 if (barrier->fetch_sub(1, std::memory_order_acq_rel) == 1)
  33.                     exit(EXIT_SUCCESS);
  34.             });
  35.             printf("submitted block %ld\n", i);
  36.         }
  37.         dispatch_main();
  38.     }
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement