MFC Thread-safe singleton - multithreading

I want to create a thread-safe singleton using only MFC. I prefer to avoid boost::thread, and I can't use std::thread on VS2010.
Also, VS 2010 has C++11 limitations (if not, it would be much easier since I think it supports thread-safe static variable initialization).
So far, I have tried this solution but I'm not sure how thread-safe it is.
From my understanding, a problem would be that the static CCriticalSection was initialized after the singleton instance is created and some trouble would appear if two threads get an instance and generate two singleton objects.
In my case there will be only two threads running simultaneously, one main thread and one worker thread. The main thread will get the first instance, and the worker threads will get instances from time to time afterwards.
In this scenario, is this class thread-safe enough? Am I missing something?
In case that there's no way to do a thread-safe enough singleton class with MFC only I'll consider boost. Any advice or suggestion is highly appreciated.
// Singleton.h
class CSingleton
{
static CCriticalSection m_cs;
public:
static CSingleton& GetInstance()
{
m_cs.Lock();
static CSingleton instance;
m_cs.Unlock();
return instance;
}
virtual ~CSingleton(){};
private:
CSingleton(){}; // Constructor
CSingleton( CSingleton const& ); // Don't Implement
void operator=( CSingleton const& );
}
// Singleton.cpp
// Initialize Critical Section
CCriticalSection CSingleton::m_cs;

Related

Appropriate use of synchronizing or locking a segment of code

Given a singleton class Employee with 2 methods
int getSalary()
void updateSalary(int increment)
Do I need to synchronize or lock both these functions or use atomic salary variable?
If yes then the question is that in this way we would have to synchronize all the functions that we define in multithreaded environment. So, why not just make synchronized a standard as today no real world application would be single threaded?
With Singleton, we always have to very careful because, singleton object being a single instance naturally, can be shared between threads. Making functions synchronized is one way, and it is not efficient way. We need to think about other aspect of concurrency, like immutability Atomic classes.
class Employee {
//singleton instantiation
private final AtomicInteger sal = new AtomicInteger(0);
int getSalary(){
return sla.get();
}
void updateSalary(int increment){
sla.add(increment);
}
}
This will solve, we do not need to synchronize every method of the singleton class.
We do not have to mark every function of every class to be synchronized, but always have to be careful if a function is modifying a state or reading a state and could be concurrently invoked, in such cases start thinking about synchronization. But, with singleton classes we always have to be careful.

Detect thread end

How can I detect when a thread was ended (in a platform independent way)?
I have to store copies of objects for every thread and I want to know when I can dispose or redistribute it.
It's possibly via RAII and local_thread mechanism. We create a class that do usefull work in destructor.
class ThreadEndNotifer
{
public:
~ThreadEndNotifer()
{
// Do usefull work
useFullWork();
}
}
Next, we create local_thread variable. It can be global or class feild(thread_local class field is implicit static).
class Foo
{
private:
// Remember about initialization like static feild
thread_local ThreadEndNotifer mNotifer;
}
So, the useFullWork will be called every time when any thread are ending.
I like to create one global variable and init it only if needed, in this way I avoid overhead.
With multiple threads, in order to detect any one of them was ended, you need:
A shared condition_variable for notification, a shared mutex to lock, and shared variables for conditions of all threads.
void call_me_at_the_end_of_a_thread(int index_of_thread){
std::unique_lock<std::mutex> l(the_global_mutex);
array_of_bools[index_of_thread] = true;
num_of_dead_threads++; // global integer only for the convenience of checking before wait
std::notify_all_at_thread_exit(the_global_condition_variable, std::move(l));
}
You may use an array of bool or vector<bool> for checking which threads was ended. You may prefer notify_all to notify_all_at_thread_exit if you don't care about the timing of notifying after current thread has finished "completely".
void call_me_to_detect_thread_was_ended(void){
static int copy_of_num_of_dead_threads;
std::unique_lock<std::mutex> l(the_global_mutex);
while(num_of_dead_threads==copy_of_num_of_dead_threads)
the_global_condition_variable.wait(l);
std::cout<<num_of_dead_threads - copy_of_num_of_dead_threads<<" threads finished.\n";
copy_of_num_of_dead_threads=num_of_dead_threads;
}
num_of_dead_threads is only for simplicity. Check the array_of_bools to find out which threads have already finished.

Run java function in thread

Is there way to run function/method in its own thread?
I have two use cases for this right now. One is that I have a Consumer<T> that is passed in. I want to run this on its own thread as it will take a long time to finish.
The other use case that I have is that I have a number of functions in the same class that I want to run in their own threads individually (one thread per function). These functions need access to private data in their class's state.
Is there a way to do this in java?
Update: For what its worth, I know about the "normal" way of doing this, either by extending Thread, or implementing runnable. However, in both of these cases those approaches don't work.
Update 2:
Implementing Runnable won't work as the class has a number of different methods that all have to be independently "run" on their own threads. Given that there are quite a few methods in this class that would need to run threads, this won't work. Since these threads require access to some shared private data, I can't even split each method into its own class (even though that would not map to what I would consider a logical class anyway).
For the case where I have a Consumer<T> I can't extend/implement Thread/Runnable as I don't control the interface. The method takes a Consumer<T> as a parameter, and I need to call it in it's own thread. I suppose here I could create a wrapper class, but then I would have to create (I think) one wrapper class each for Consumer, Function, etc. And all of this seems rather needless (at least coming from other languages).
Update 3: Assume that synchronization is not an issue (data is either immutable, or contention is very low)
I am looking for a better way. Is this clearer?
As a partial solution for the functions / methods (if they don't need arguments) you can use Threads or an ExecutorService and method references.
If you need arguments you will have to write lambda expressions - see the method t3 and it's start for an example.
public class Test {
public void t1() {
System.out.println("t1");
}
public void t2() {
System.out.println("t2");
}
public void t3(int n) {
System.out.println("t3:"+n);
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
Thread t = new Thread(test::t1);
t.start();
ExecutorService es = Executors.newFixedThreadPool(5);
es.submit(test::t2);
es.submit(() -> test.t3(99));
es.shutdown();
es.awaitTermination(1, TimeUnit.SECONDS);
}
}

What does really happen if I access a singleton in a multithreaded Program

EDIT: Ok, it works now. I don't know exactly what was the worst problem, but i haven't done some locking which was needed to avoid race conditions. Also i added the "volatile" key-word to the deklaration of the instance variable of the singleton.
if i have some threads running and in one thread i access a singleton (which was maybe created in another thread), i get a fresh "singleton" in terms of that the constructor of the singleton is called for every thread who access it in his memory space the first time? Have i understood this right?
The problem is in my application i have a singleton created by the main thread. If i then call Singleton.Instance.somemethod(...) i get always null pointer exceptions or empty lists, even if the lists were created and filled in the main thread?
Is there a way to handle that problem, so that i can use the same instance of the singleton in all threads running? Some way of synchronizing the whole instance?
Thank you.
EDIT: Sorry lacking some really important information. I am using C# and the .NET Framework 4.0 under Visual Studio 2010 Professional.
I create the Singleton this way:
static readonly object _padlock = new object();
public static StaticAnalyzer Instance
{
get
{
lock (_padlock)
{
if (_instance == null)
{
_instance = new StaticAnalyzer();
}
return _instance;
}
}
}
In the background every thread has its own virtual memory space or not? So if i create the singleton in the main thread and then in create some worker threads with the task.factory and the worker threads call the instance, why does they get the real singleton? because of the static keyword?
No, a singleton (if implemented correctly) will be just one for all the threads. Like System.DBNull. Otherwise it's not a singleton. You must have a mistake in your code somewhere.

QNetworkAccessManager from ThreadPool

A very fundamental question. The documentation mentions that all methods in QNetworkAccessManager are reentrant. If so, is performing a get() method in a QRunnable without locks legal? My code would look something like this:
class MyClass: public QRunnable
{
void run()
{
...
QNetworkAccessManager nam;
QNetworkReply* reply = name.get(request) // No Read-write lock.
...
}
};
From the Qt documentation:
[...] a class is said to be reentrant if its member functions can [simultaneously] be
called safely from multiple threads, as long as each thread uses a different instance of
the class.
Since you're using a different instance each time (the one you create on the stack in run()), you're on the safe side.
As a side note to this ,if you just want the GET request to be asynchronous, QNetworkAccessManager is already asynchronous (says so in the docs).

Resources