How to multi-thread this?

Posted by WilliamKF on Stack Overflow See other posts from Stack Overflow or by WilliamKF
Published on 2010-05-25T02:10:46Z Indexed on 2010/05/25 3:11 UTC
Read the original article Hit count: 135

Filed under:
|
|
|

I wish to have two threads. The first thread1 occasionally calls the following pseudo function:

void waitForThread2() {
  if (thread2 is not idle) {
    return;
  }
  notifyThread2IamReady();
  while (thread2IsExclusive) {
  }
}

The second thread2 is forever in the following pseudo loop:

for (;;) {
  Notify thread1 I am idle.
  while (!thread1IsReady()) {
  }
  Notify thread1 I am exclusive.
  Do some work while thread1 is blocked.
  Notify thread1 I am busy.
  Do some work in parallel with thread1.
}

What is the best way to write this such that both thread1 and thread2 are kept as busy as possible on a machine with multiple cores. I would like to avoid long delays between notification in one thread and detection by the other. I tried using pthread condition variables but found the delay between thread2 doing 'notify thread1 I am busy' and the loop in waitForThread2() on thear2IsExclusive() can be up to almost one second delay. I then tried using a volatile sig_atomic_t shared variable to control the same, but something is going wrong, so I must not be doing it correctly.

© Stack Overflow or respective owner

Related posts about c++

Related posts about pthreads