1 - What the name for this form of in-code function, it's look like some event management code on java ?
2 - I suppose that the content of [] is the function execution context ?
3 - I want to undestand :
* What i need to put under [] ?
* What is the default value when [] is empty ?
* Is there multi-threading constraint(s) or issue(s)...
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
// Wait until main() sends data
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
//after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";
// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";
// Manual unlocking is done before notifying, to avoid
// that the waiting thread gets blocked again.
lk.unlock();
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
// wait for the worker
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return processed;});
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
}
Hiya. What you have there is a lambda, which is essentially a like a function, with some differences (notably, you can make it so that the variables that are visible in the scope the lambda was declared in are accessible within the lambda, a useful feature).