简体   繁体   English

C ++ 11线程,它是有效的代码吗?

[英]C++11 Threads, is it valid code?

I am playing around with threads features of C++11. 我在玩C ++ 11的线程功能。 But the following code does not compile under both clang (3.5) and gcc (4.9.2). 但是以下代码无法同时在clang(3.5)和gcc(4.9.2)下编译。

#include <iostream>
#include <thread>

void add(int& x) {
    x += 1;
}

int main (int argc, char const *argv[])
{
    int x{ 5 };
    int y{ 8 };

    std::thread my_thread_1{ add, x };
    std::thread my_thread_2{ add, y };
    my_thread_1.join();
    my_thread_2.join();

    std::cout << x << " " << y << std::endl;

    return 0;
}

Is it valid C++11? 它是有效的C ++ 11吗?

It's valid, but the thread class copies its arguments, so you can't use references directly. 它是有效的,但是线程类复制其参数,因此您不能直接使用引用。 You have to use std::ref to make it work: 您必须使用std::ref使其起作用:

std::thread my_thread_1{ add, std::ref(x) };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM