0

i have this c++ simple factory method :

class Vehicle {
public:
    virtual void printVehicle() = 0;
    static Vehicle* Create(VehicleType type);
    virtual ~Vehicle(){}
};
    Vehicle* Vehicle::Create(VehicleType type) {
        if (type == VT_TwoWheeler)
            return new TwoWheeler();
        else if (type == VT_ThreeWheeler)
            return new ThreeWheeler();
        else if (type == VT_FourWheeler)
            return new FourWheeler();
        else return NULL;
    }

I want that this factory method will when called from more then 1 thread be protected and return New Object to the caller thread only . other threads will wait in java i guess its something like :

synchronized (Vehicle .class) {
   .. protected code ...
}

How can it done in c++14 ?

user63898
  • 29,839
  • 85
  • 272
  • 514
  • This method __is__ threadsafe. – tkausl Jan 14 '23 at 20:50
  • As in, the default global allocator is thread safe. – StoryTeller - Unslander Monica Jan 14 '23 at 20:50
  • 1
    The return value is only ever returned to the caller. what makes you think other threads could get the object? – Homer512 Jan 14 '23 at 21:14
  • @tkausl how come ? can't more then 1 thread call the factory method in paralele ? – user63898 Jan 15 '23 at 03:33
  • 1
    If those 'TwoWheeler()' etc. ctors are thread-safe, you should be OK, yes. Is there some reason for your doubt? – Martin James Jan 15 '23 at 08:51
  • The data within a function (local variables) are always private to a thread. Each has their own copy. Therefore you don't have to protect anything. What you have to protect is shared read-write data (read-only is fine). Your code does not feature any of that. Examples that could come up are a) shared objects such as the same object being modified from different threads b) static class attributes c) global variables – Homer512 Jan 15 '23 at 09:58
  • @Homer512 how i do protect that ? – user63898 Jan 16 '23 at 06:45
  • You store an [`std::mutex`](https://en.cppreference.com/w/cpp/thread/mutex) and lock it at the start of the method with an [`std::unique_lock`](https://en.cppreference.com/w/cpp/thread/unique_lock) – Homer512 Jan 16 '23 at 08:46
  • See also here: https://stackoverflow.com/questions/26177784/is-it-possible-to-have-java-like-synchronization-statements-in-c-c – Homer512 Jan 16 '23 at 08:56

0 Answers0