-1

I want to initialize the uniqe lock in the c'tor and I did not find the way...

class readersWriters{
private:
mutex _mu;
unique_lock<mutex> _locker;
condition_variable _condW;
condition_variable _condR;
int _readersNumber;
int _writersNumber;
std::string _fileName;

public:
readersWriters(std::string fileName);
void readLock();
void writeLock();
void readUnlock();
void writeUnlock();
std::string readLine(int lineNumber); //lineNumber - line number to read
void WriteLine(int lineNumber, std::string newLine);//lineNumber - line    number to write 
};

Thanks for the help

lee78
  • 13
  • 4

1 Answers1

0

I'm not sure if this is a good idea, but to apply correct syntax you would need your constructors member initializer list:

 readersWriters(string fileName) : _mu(), _locker(_mu) {}

Be aware that this makes your whole class definition merely a proxy of the _locker, and the mutex stays locked over your classes whole lifetime.

Thus it doesn't make much sense as long _mu is a member of that class.

If your class uses threads internally, you rather should use unique_lock as local variables in functions that can be called concurrently.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • But I need also initialize the mutex before it – lee78 Jan 21 '16 at 18:06
  • @SamCristall, true. Comments do not have the space to list all restrictions :), I was arguing general case. – SergeyA Jan 21 '16 at 18:06
  • Not sure if you want to call it out or not but this may only work if the mutex is listed before the lock in the class. If it is the other way the lock would get initialized before the mutex is. – NathanOliver Jan 21 '16 at 18:15
  • I write to file with different threads so i want to lock it every time that one if the threads is writing so I'll lock it at that time – lee78 Jan 21 '16 at 18:25
  • @lee78 Of course. As mentioned it doesn't make sense to use a `unique_lock` class wide. See the [examples](http://en.cppreference.com/w/cpp/thread/unique_lock) at the reference documentation. It's meant for local scopes. – πάντα ῥεῖ Jan 21 '16 at 18:26
  • It is not my full class I wrote only what is relevant to my question – lee78 Jan 21 '16 at 18:31
  • @lee78 May be you narrowed it too much. – πάντα ῥεῖ Jan 21 '16 at 18:32
  • see my update for the class @πάνταῥεῖ – lee78 Jan 21 '16 at 18:34
  • @lee78 So you want to do the locking manually? Or see, if implementing a read/write lock yourself might serve you better: [How would a readers/writer lock be implemented in C++11?](http://stackoverflow.com/questions/12033188/how-would-a-readers-writer-lock-be-implemented-in-c11) – πάντα ῥεῖ Jan 21 '16 at 18:38
  • @πάνταῥεῖ I love to do it like this but it is a written assignment but tanks – lee78 Jan 21 '16 at 18:50