开发者

How to create a barrier in multi-thread on android

开发者 https://www.devze.com 2023-04-07 06:04 出处:网络
I need a barrier in my multi-thread project on Linux. I know the pthread_barrier_init() and pthread_b开发者_开发技巧arrier_wait(), but I want to run my project on android. It didn\'t have these functi

I need a barrier in my multi-thread project on Linux. I know the pthread_barrier_init() and pthread_b开发者_开发技巧arrier_wait(), but I want to run my project on android. It didn't have these functions. I know how to implement it with atomic add and atomic comparison. I want to use a semaphore, can I use a semaphore to implement it?


Use a CyclicBarrier, this is more or less identical to a pthread barrier.

Sample code (from linked page)

 class Solver {
   final int N;
   final float[][] data;
   final CyclicBarrier barrier;

   class Worker implements Runnable {
     int myRow;
     Worker(int row) { myRow = row; }
     public void run() {
       while (!done()) {
         processRow(myRow);

         try {
           barrier.await();
         } catch (InterruptedException ex) {
           return;
         } catch (BrokenBarrierException ex) {
           return;
         }
       }
     }
   }

   public Solver(float[][] matrix) {
     data = matrix;
     N = matrix.length;
     barrier = new CyclicBarrier(N,
                                 new Runnable() {
                                   public void run() {
                                     mergeRows(...);
                                   }
                                 });
     for (int i = 0; i < N; ++i)
       new Thread(new Worker(i)).start();

     waitUntilDone();
   }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号