1

I have a process which need to listen and handle.

to be specific, I need to listen from two shared memory, and whenever there are new data arrived. I need to handle it. meanwhile, i don't want one data block the other, so, I let them run in separate thread.

here is a demo code:

void RunFirst() {
  while (true) {
    std::string s;
    shm1_->Recv(&s);
    // handle 1
  }
}

void RunSecond() {
  while (true) {
    std::string s;
    shm2_->Recv(&s);
    // handle 2
  }
}

void start() {
  std::thread t(RunFirst);
  RunSecond();
}

I have two shm object, which are two shared memory Recviver. they loop to listen if there is data.

it runs well which can handle whenever data comes. and wont let one data blocks another.

but the problem is the high CPU usage. it make two CPU runs in 100% usage.

Is there any methods can decrease CPU usage and keep the unblock?

nothingisme
  • 119
  • 5
  • 1
    I am not sure what you have here or how Recv function works as you haven't posted it. Normally, with shared memory one uses a piece of it for semaphores uses them to signal data update/renewal. Or some similar protocol. I have no idea what you have implemented. – ALX23z Mar 05 '23 at 04:34
  • need to see what Recv does – pm100 Mar 05 '23 at 04:45
  • Your description suggests your Recv() function is busy-waiting, producing the high CPU load. If receiving from another thread, use a [condition_variable](https://en.cppreference.com/w/cpp/thread/condition_variable) (or, if c++20, maybe a [semaphore](https://en.cppreference.com/w/cpp/thread/counting_semaphore)) to avoid busy-waiting. If you're sharing memory with another process, try [reading this thread](https://stackoverflow.com/questions/8359322/how-to-share-semaphores-between-processes-using-shared-memory). – Perette Mar 05 '23 at 05:11
  • @Perette he has shared memory between multiple processes... I doubt that `std::condition_variable` is suitable for the task. – ALX23z Mar 05 '23 at 05:24
  • By the way, a string is constantly allocated for each operation which might be expensive (though unlikely to be the root of the issue). – Jérôme Richard Mar 05 '23 at 11:18
  • @pm100 sorry for that, i added details here. https://stackoverflow.com/questions/75641960/how-to-reduce-cpu-usage-in-multi-producer-multi-consumer-shared-memory-ipc. will close this later – nothingisme Mar 05 '23 at 11:42
  • @ALX23z sorry for that, i added details here. https://stackoverflow.com/questions/75641960/how-to-reduce-cpu-usage-in-multi-producer-multi-consumer-shared-memory-ipc. will close this later – nothingisme Mar 05 '23 at 11:43

0 Answers0