[cpp-threads] N2907 examples using new_thread_local { }

Alexander Terekhov alexander.terekhov at gmail.com
Fri Jul 3 18:08:49 BST 2009


Just a thought regarding

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2907.html

* * *

std::mutex task_mutex;
std::queue<std::function<void()>> tasks;
std::condition_variable task_cond;
bool done=false;

void worker_thread() {
    std::unique_lock<std::mutex> lk(task_mutex);
    while(!done) {
        task_cond.wait(lk,[]{return !tasks.empty();});
        std::function<void()> task=tasks.front();
        tasks.pop_front();
        lk.unlock();
        new_thread_local {  task();  }
        lk.lock();
    }
}

* * *

static thread_local int i=0;

int main() {
    i=42;
    new_thread_local {
        std::cout<<i<<",";
        i=123;
    }
    std::cout<<i<<std::endl;
}

* * *

static thread_local int i=0;

int main() {
    i=42;
    int* p=&i;
    new_thread_local {
        std::cout<<i<<",";
        std::cout<<*p<<",";
        *p=99;
        i=123;
    }
    std::cout<<i<<std::endl;
}

It just looks much prettier to me. ;-)

regards,
alexander.



More information about the cpp-threads mailing list