c++ – C ++ asynchronous infinite loop

Question:

Hello. I have an endless loop. At startup, as expected, the program hangs, nothing is pressed. How can you run this loop asynchronously? Not very strong in C ++ , I need a simple example. Thank you)

for (size_t i = 0; i < INFINITY; i++) {
    somefunction();
}

Answer:

Using std::thread , I made an endless loop inside a separate thread, which can be passed to a pointer to false and then the loop in the thread will stop.

bool *ptrStatus = &status;
*ptrStatus = false;

The variables status and interval have a global scope.

The code:

bool status = true;
int interval = 1;

void startNewThread(int interval) {
    thread newThread(setWallpaper, &status, interval);
    newThread.detach();
};

int setWallpaper(bool *status, int interval) {
   while (true) {
      if (*status == false) return 0;
      wstring path = getPath();
      SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID)path.c_str(), SPIF_UPDATEINIFILE);
      this_thread::sleep_for(chrono::seconds(interval));
   }
}
Scroll to Top