QThreadPool::jobQueueSize() ? QThreadPool::finishedJobCount() - multithreading

Is there any way to know how many jobs it has finished executing ? e.g. why there is no method like QThreadPool::jobQueueSize() or QThreadPool::finishedJobCount() or QThreadPool::waitingJobCount().
I see Nither do QRunnables offer any such functionality. like started() or finished()
Should I do a Hack like. in QRunnable::run()
/**
* Assuming _controller has a link to all the Runnables. and I've a finite number of QRunnables that I recycle in my own Way.
*/
void MyRunnable::run(){
mutex.lock();
_controller->markAsStarted(this);
mutex.unlock();
....
mutex.lock();
_controller->markAsFinished(this);
mutex.unlock();
}

QThreadPool is a singleton and uses the interface implementation idiom. Which means that the actual implementation is performed by QThreadPoolPrivate class and QThreadPool is just the interface.
First alternative:
You need to patch QThreadPoolPrivate to get the methods that you want.
Next you need to patch QThreadPool to return its hidden QThreadPoolPrivate implementation
so that you can access this internal class
Second alternative :
Patch the constructor of QThreadPool to inject your own implementation that provides the methods that you need.
In both cases you need to patch Qt's source code.

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.

MFC Thread-safe singleton

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;

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);
}
}

How do I create a scheduler which never executes more than one Task at a time using async-await?

I want to implement a class or pattern that ensures that I never execute more than one Task at a time for a certain set of operations (HTTP calls). The invocations of the Tasks can come from different threads at random times. I want to make use of the async-await pattern so that the caller can handle exceptions by wrapping the call in a try-catch.
Here's an illustration of the intended flow of execution:
Pseudo code from caller:
try {
Task someTask = GetTask();
await SomeScheduler.ThrottledRun(someTask);
}
catch(Exception ex) {
// Handle exception
}
The Taskclass here might instead be an Action class depending on the solution.
Note that I when I use the word "Schedule" in this question I'm not necessarily using it with relation to the .NET Task Scheduler. I don't know the async-await library well enough to know at what angle and with what tools to approach this problem. The TaskScheduler might be relevant here, and it may not. I've read the TAP pattern document and found patterns that almost solve this problem, but not quite (the chapter on interleaving).
There is a new ConcurrentExclusiveSchedulerPair type in .NET 4.5 (I don't remember if it was included in the Async CTP), and you can use its ExclusiveScheduler to restrict execution to one Task at a time.
Consider structuring your problem as a Dataflow. It's easy to just pass a TaskScheduler into the block options for the parts of the dataflow you want restricted.
If you don't want to (or can't) use Dataflow, you can do something similar yourself. Remember that in TAP, you always return started tasks, so you don't have the "creation" separated from the "scheduling" like you do in TPL.
You can use ConcurrentExclusiveSchedulerPair to schedule Actions (or async lambdas without return values) like this:
public static ConcurrentExclusiveSchedulerPair schedulerPair =
new ConcurrentExclusiveSchedulerPair();
public static TaskFactory exclusiveTaskFactory =
new TaskFactory(schedulerPair.ExclusiveScheduler);
...
public static Task RunExclusively(Action action)
{
return exclusiveTaskFactory.StartNew(action);
}
public static Task RunExclusively(Func<Task> action)
{
return exclusiveTaskFactory.StartNew(action).Unwrap();
}
There are a few things to note about this:
A single instance of ConcurrentExclusiveSchedulerPair only coordinates Tasks that are queued to its schedulers. A second instance of ConcurrentExclusiveSchedulerPair would be independent from the first, so you have to ensure the same instance is used in all parts of your system you want coordinated.
An async method will - by default - resume on the same TaskScheduler that started it. So this means if one async method calls another async method, the "child" method will "inherit" the parent's TaskScheduler. Any async method may opt out of continuing on its TaskScheduler by using ConfigureAwait(false) (in that case, it continues directly on the thread pool).

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