Limiting mutex scope using blocks in header [duplicate] - c++

This question already has answers here:
Mutex example / tutorial? [closed]
(7 answers)
Closed 6 years ago.
I have a class that has its own worker thread, and some of the member variables of the class is shared between the main thread and the worker. How can I use a mutex to lock only the member variables that are being shared?
For instance, this does not work (since the block scope is outside any function).
class Foo {
public:
// Some stuff
private:
boost::thread *m_worker;
Bar m_bar_nonshared;
{
boost::mutex m_mutex;
Bar m_bar_shared;
}
};

A mutex doesn't lock member variables, it locks code. The only way for it to lock a member variable is if it locks the only code that accesses it.
That is, put the lock in the access functions (get/set) and don't allow access to the members any other way.

Related

Thread in C++11 not in class member [duplicate]

This question already has answers here:
Start thread with member function
(5 answers)
Closed 5 years ago.
I'm recently using C++11 threads and I have a question about something (strange for me) happened.
I created a method inside a class, able to start thread. The starting thread method and the callback function of the thread are class methods.
To clarify, in my Person.cpp file I have:
void Person::callbackForThread(){
...
}
void Person::startThread(){
this call threads. Something like:
thread(callbackForThread);
}
The problem is that C++11 doesn't allow me to declare these two function as class methods. This means that if I declare them as normal function, i.e:
void callbackForThread(){
...
}
void startThread(){
this call threads. Something like:
thread(callbackForThread);
}
Everythings works. I would know how could I declare thread and callback inside a class in C++, if it is possible.
For the farther, I have omitted the inclusion of the libraries and the name of the real class. The class shown in this question is fictitious.
This is because Person::callbackForThread takes an hidden first argument: this.
This is where lambdas and std::bind come in handy:
thread([this]() { this->callbackForThread(); });
or
using namespace std::placeholders;
thread(std::bind(&Person::callbackForThread, this, _1));
From krzaq feedback: if thread is std::thread, it needs to be detached or saved somehow.

Singleton - multithreaded issue in C++ [duplicate]

This question already has answers here:
Is Meyers' implementation of the Singleton pattern thread safe?
(6 answers)
Closed 6 years ago.
I've seen posts about this issue but I'm still trying to figure it out. Is this way alright for implementing a safe singelton? I'm using mutex, static member and return its reference.
#include <mutex>
using namespace std;
mutex mtx;
class MySingleton {
private:
MySingleton();
public:
MySingleton& getInstance() {
mtx.lock();
static MySingleton instance;
mtx.unlock();
return instance;
}
};
Is this way alright for implementing a safe singelton?
It's overshoot. Just get rid of the mutex and write:
static MySingleton& getInstance() {
static MySingleton instance;
return instance;
}
The thread safe creation of instance is guaranteed when the function is called the 1st time.

Thread constructor syntax - passing class members by reference [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Start thread with member function
I have recently been playing around with the new std::thread library in c++11 and I came across a problem. When i try to pass a classes function into a new thread, it gives me an error (I dont have the exact error text right now since im away from home)
I had a class like this
class A
{
void FunctA();
void FunctB();
void run()
{
std::thread t(FunctA);
std::thread r(FunctB);
}
}
What am I doing wrong?
class A
{
void FunctA();
void FunctB();
void run()
{
std::thread t(&A::FunctA, this);
std::thread r(&A::FunctB, this);
}
};
Pointers to member functions are different from pointers to functions, syntax of calling them is different, as well, and requires instance of class. You can just pass pointer to instance as second argument of std::thread constructor.
I think, the problem is that you can't get pointer to member function in a way similar to functions. Here you will find more information about this.
Also, it would be much easier to answer, if you provided compipler error text.

Why undefined referenced to mMutex in my singleton class [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
Closed 8 years ago.
I have implemented a Meyer's singleton pattern. And I try to do some stuff testing it in a multithreading environment. Here is how I implemented the class in C++.
#include<thread>
#include<mutex>
class singleton {
public:
static singleton& instance() {
std::lock_guard<std::mutex> lck(mtx);
static singleton *my = new singleton;
return *my;
}
private:
static std::mutex mtx;
singleton() {}
~singleton() {}
singleton(const singleton &) {}
singleton& operator=(const singleton &) {}
};
But when I compile this with g++ -std=c++11 singleton.cpp -o singleton -lpthread, it says
/tmp/ccfEBnmN.o: In function `singleton::instance()':
singleton.cpp(.text._ZN11singleton12instanceEv[_ZN11singelton12instanceEv]+0x10):
undefined reference to `singleton::mtx' collect2: error: ld returned 1 exit status
I understand this might be some problem in design, since without initializing the first singleton instance how could we get the mtx. If in this case, my question comes to how to implement a thread safe singleton class based on my code? How do we initialized the mtx in my singleton class?
I know there is a traditional way to create a singleton pattern by maintaining a static pointer points to the singleton class. But indeed that is not "so" thread safe. Even applying the double check mechanism in the instance() method.
You've declared mtx in singleton, but failed to define it, which has to be outside of singleton, something like this:
std::mutex singleton::mtx;
This should be in a source file, not a header though (otherwise you'll get multiple definition errors when/if you include the header in more than one source file).
Second point: what you're showing is not a Meyer's singleton pattern at all. For a Meyer's singleton, you define a static instance of the singleton inside the function:
static singleton &instance() {
static singleton my;
return my;
}
Using this, it's not clear that you really need a mutex at all.
Your static data member mtx needs a definition. Place this in your source file:
std::mutex singleton::mtx;
More accurately, std::lock_guard<std::mutex> lck(mtx) odr-uses mtx so its definition is required. You get a link-time error when the linker cannot resolve the reference.
Also note that in C++11 the initialization of an object with static storage duration is thread safe, you don't need a mutex.

Why pthread_mutex_t can't be static field of class ? [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
C++ - Initialize and modify a static class member
(4 answers)
Closed 9 years ago.
I have problem with pthread_mutex_t. When I try to create static field pthread_mutex_t, then initialize it in static function and finally use it within some class methods I get many errors like:
main.o: In function `LogWriter::initialize(pthread_mutex_t*)':
main.cpp:(.text._ZN9LogWriter10initializeEP15pthread_mutex_t[LogWriter::initialize(pthread_mutex_t*)]+0x7): undefined reference to `LogWriter::mutex'
Simpplified class code:
class LogWriter{
static pthread_mutex_t mutex;
static void initialize(pthread_mutex_t *mut){
LogWriter::mutex = PTHREAD_MUTEX_INITIALIZER;
//if(pthread_mutex_init(&(LogWriter::mutex), NULL) != 0){
//init failed
//}
}
public:
static LogWriter getInstance(string module_name){
LogWriter instance(module_name);
return instance;
}
LogWriter& operator<<(string a);
};
My quesiton is: why ? I know that if I define it as normal (non-static) field I won't have any problems. Also searched google but I couldn't find any materials that are linked with this.
Also creating pointer to static pthread_mutex and initializing in in main function ends like this.
In some source file in your code, you need to add:
static LogWriter::pthread_mutex_t mutex;
The compiler won't "place" your variable in any particular source file, you have to do that for it. The class declaration just tells the compiler "I'll have a static variable somewhere" - but since, at least in theory, variables ordering and placement can make a difference [you may for example have different object files product "data" that goes into different sections of memory in some embedded system], the compiler won't be able to just throw it in any place it likes - that could be somewhere you don't want it.