c++11 : [] { return m_bState; }

Hi,

I am reading c+11 from Stroustrup... and i am in trouble to understand this king of things :
1
2
3
4
5
6
7

  []{return ready;}

  [&]{return ready;}

  [this]{return ready;}


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)...


An example from an other site ~o~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#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();
}


Thanks for your help,

WCdr
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).

This will explain all you need to know:
http://en.cppreference.com/w/cpp/language/lambda

-Albatross
Thanks ^_^
Topic archived. No new replies allowed.