结合C++ concurrency in action
Passing data to a thread by value
#include <iostream>
#include <thread>
#include <future>
class Vehicle
{
public:
//default constructor
Vehicle() : _id(0)
{
std::cout << "Vehicle #" << _id << " Default constructor called" << std::endl;
}
//initializing constructor
Vehicle(int id) : _id(id)
{
std::cout << "Vehicle #" << _id << " Initializing constructor called" << std::endl;
}
// setter and getter
void setID(int id) { _id = id; }
int getID() { return _id; }
private:
int _id;
};
int main()
{
// create instances of class Vehicle
Vehicle v0; // default constructor
Vehicle v1(1); // initializing constructor
// read and write name in different threads (which one of the above creates a data race?)
std::future<void> ftr = std::async([](Vehicle v) {
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // simulate work
v.setID(2);
}, v0);
v0.setID(3);
ftr.wait();
std::cout << "Vehicle #" << v0.getID() << std::endl;
return 0;
}
如果改为pass by reference:
int main()
{
// create instances of class Vehicle
Vehicle v0; // default constructor
Vehicle v1(1); // initializing constructor
// read and write name in different threads (which one of the above creates a data race?)
std::future<void> ftr = std::async([](Vehicle& v) {
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // simulate work
v.setID(2);
}, std::ref(v0));
v0.setID(3);
ftr.wait();
std::cout << "Vehicle #" << v0.getID() << std::endl;
return 0;
}
就算是pass by value, 也有可能出现data被modify的情况,比如pointer
#include <iostream>
#include <thread>
#include <future>
class Vehicle
{
public:
//default constructor
Vehicle() : _id(0), _name(new std::string("Default Name"))
{
std::cout << "Vehicle #" << _id << " Default constructor called" << std::endl;
}
//initializing constructor
Vehicle(int id, std::string name) : _id(id), _name(new std::string(name))
{
std::cout << "Vehicle #" << _id << " Initializing constructor called" << std::endl;
}
// setter and getter
void setID(int id) { _id = id; }
int getID() { return _id; }
void setName(std::string name) { *_name = name; }
std::string getName() { return *_name; }
private:
int _id;
std::string *_name;
};
int main()
{
// create instances of class Vehicle
Vehicle v0; // default constructor
Vehicle v1(1, "Vehicle 1"); // initializing constructor
// launch a thread that modifies the Vehicle name
std::future<void> ftr = std::async([](Vehicle v) {
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // simulate work
v.setName("Vehicle 2");
},v0);
v0.setName("Vehicle 3");
ftr.wait();
std::cout << v0.getName() << std::endl;
return 0;
}
This happens because the member _name is a pointer to a string and after copying, even though the pointer variable has been duplicated, it still points to the same location as its value (i.e. the memory location) has not changed.
Classes from the standard template library usually implement a deep copy behavior by default (such as std::vector). When dealing with proprietary data types, this is not guaranteed. The only safe way to tell whether a data structure can be safely passed is by looking at its implementation: Does it contain only atomic data types or are there pointers somewhere? If this is the case, does the data structure implement the copy constructor (and the assignment operator) correctly? Also, if the data structure under scrutiny contains sub-objects, their respective implementation has to be analyzed as well to ensure that deep copies are made everywhere.
Overwriting copy constructor可以一定程度解决这个问题
Default的copy constructor对于指针的copy是只copy指针本身,但新copy出来的指针和原指针实际上指向同一object. This behavior is also referred to as "shallow copy". we would have liked (and maybe expected) a "deep copy" of the object though, i.e. a copy of the data to which the pointer refers
// copy constructor
Vehicle(Vehicle const &src)
{
_id = src._id;
if (src._name != nullptr)
{
_name = new std::string;
*_name = std::move(*src._name);
}
std::cout << "Vehicle #" << _id << " copy constructor called" << std::endl;
};
BTW, * in *src is indirection operator, it takes the value available at src
重写copy constructor比较繁琐,更进一步的做法是Passing data using move semantics
#include <iostream>
#include <thread>
#include <future>
class Vehicle
{
public:
//default constructor
Vehicle() : _id(0), _name(new std::string("Default Name"))
{
std::cout << "Vehicle #" << _id << " Default constructor called" << std::endl;
}
//initializing constructor
Vehicle(int id, std::string name) : _id(id), _name(new std::string(name))
{
std::cout << "Vehicle #" << _id << " Initializing constructor called" << std::endl;
}
// copy constructor
Vehicle(Vehicle const &src)
{
//...
std::cout << "Vehicle #" << _id << " copy constructor called" << std::endl;
};
// move constructor
Vehicle(Vehicle && src)
{
_id = src.getID();
_name = new std::string(src.getName());
src.setID(0);
src.setName("Default Name");
std::cout << "Vehicle #" << _id << " move constructor called" << std::endl;
};
// setter and getter
void setID(int id) { _id = id; }
int getID() { return _id; }
void setName(std::string name) { *_name = name; }
std::string getName() { return *_name; }
private:
int _id;
std::string *_name;
};
int main()
{
// create instances of class Vehicle
Vehicle v0; // default constructor
Vehicle v1(1, "Vehicle 1"); // initializing constructor
// launch a thread that modifies the Vehicle name
std::future<void> ftr = std::async([](Vehicle v) {
v.setName("Vehicle 2");
},std::move(v0));
ftr.wait();
std::cout << v0.getName() << std::endl;
return 0;
}
To define a move constructor for a C++ class, the following steps are required:
- Define an empty constructor method that takes an rvalue reference to the class type as its parameter
- In the move constructor, assign the class data members from the source object to the object that is being constructed
- Assign the data members of the source object to default values.
网友评论