简体   繁体   中英

Pause a loop till a bool changes

I am trying to make RPC calls to a daemon. Now the issue is. I want to make multiple async RPC calls, that'd choke the message buffer. So I want to do it one by one. what I am following

bool wait;

success(){
        // On success from send_to_single_peer this will run
        wait = false;
}

send_to_single_peer(peer){
              wait = true
             //makes an RPC call for sendcustommsg to a peer and goes to sucess function
}

sendmultipleasync(){
             for(//conditions) {
                    send_to_single_peer(peer[i]);
                    do{}
                    while(wait)
             }
}

But this isn't working. What should I do? I've heard multithreading can help me in this case. But I don't know about that much.

I think you need. Your function has the name async in it, so why not do it async.

  1. create a worker thread
  2. create a mutex
  3. make the worker thread lock the mutex
  4. for every peer:
    1. send the request
    2. did it work? if not try again
  5. unlock the mutex (all done)

While you are doing that, you can check if the worker thread is done by using pthread_mutex_trylock . If you just want to wait until it is done use pthread_mutex_lock . NEVER USE while (pthread_mutex_trylock(mutex)); TO DO THAT.

I've heard multithreading can help me in this case. But I don't know about that much.

Basically, with threads you can execute code in parallel. The problem is, that they share the heap memory and are able to modify the variables while the other threads are trying to use them. This will lead to problems really hard to debug, sometimes they only occur one time in a million, because they depend on timing. To prevent access at the same time you can use a mutex . It is kind of a lock for threads. A mutex can only be locked once at a time. One thread for example can lock a mutex while changing a variable. The other thread can try to lock it too. This will cause it to block until the first thread unlocks the mutex. After that block the second thread can read the variables and unlock the mutex after that.

Read a tutorial on threads, they are a really useful took.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM