When i creating TThread i can't pass parameters to thread, so i need use global variables or what?
I am using Embarcaderos Rad Studio C++ Builder 2010
You have a class derived from TThread, right? Can you just make your class constructor take additional arguments (beyond the bool suspended one that seems to be common)?
An alternative to providing a different constructor is to simply assign properties of the thread between the time you create the object and the time you start it.
bool suspended = true;
TSergeyThread* thread = new TSergeyThread(suspended);
thread->Property1 = 4;
thread->SetValue("foo");
thread->Start(); // or ->Resume(), if your VCL is too old
Better is to provide all that information in the constructor, though. (RAII, and all that.)
Related
I'm using threaded application written in Qt (C++).
I need to make get/post request very often from separate threads.
Qt doc says:
One QNetworkAccessManager instance should be enough for the whole Qt
application. Since QNetworkAccessManager is based on QObject, it can
only be used from the thread it belongs to.
Is static thread_local QNetworkAccessManager good choice for my purpose?
No, not a good choice.
You shouldn't create static or global QObject subclass instances, because you generally need them to be created after the Qt application object has been created (a lot of Qt stuff depends on the application object existing already). C++ does not really provide very good control over when static objects are actually created, and here you want to have that control.
Just use a pointer and new to create the QNetworkAccessManager instance, as many of them as you want. You could create them in the right thread directly, or you could create them in some other (usually main) thread and move them to the right thread.
To get them destroyed properly, when they don't have a natural parent (because the parent must live in the same thread!), connect the their thread's QThread::finished signal to the objects QObject::deleteLater slot, and they will get cleanly deleted when the thread finishes.
If you want a plain function, which uses the current thread's QNAM instance, you could have thread-local static pointer. Something like
static thread_local *thread_qnam;
void myfunc() {
if (!thread_qnam) {
thread_qnam = new QNetworkAccessManager;
connect(QThread::currentThread, &QThread::finished(), thread_qnam, &QObject::deleteLater);
// Whatever other setup you need.
// It'd probably be good idea to wrap this in a function.
}
// Use thread_qnam...
}
I have a singleton class for logging purpose in my Qt project. In each class except the singleton one, there is a pointer point to the singleton object and a signal connected to an writing slot in the singleton object. Whichever class wants to write log info just emit that signal. The signals are queued so it's thread-safe.
Please critique this approach from OOP point of view, thanks.
=============================================================================================
Edit 1:
Thank you all your applies, listening to opposite opinions is always a big learning.
Let me explain more about my approach and what I did in my code so far:
Exactly as MikeMB pointer, the singleton class has a static function like get_instance() that returns a reference to that singleton. I stored it in a local pointer in each class's constructor, so it will be destroyed after the constructor returns. It is convenient for checking if I got a null pointer and makes the code more readable. I don't like something as this:
if(mySingletonClass::gerInstance() == NULL) { ... }
connect(gerInstance(), SIGNAL(write(QString)), this, SLOT(write(QString)));
because it is more expensive than this:
QPointer<mySingletonClass> singletonInstance = mySingletonClass::getInstance();
if(singletonInstance.isNull) { ... }
connect(singletonInstance, SIGNAL(write(QString)), this, SLOT(write(QString)));
Calling a function twice is more expensive than creating a local variable from ASM's point of view because of push, pop and return address calculation.
Here is my singleton class:
class CSuperLog : public QObject
{
Q_OBJECT
public:
// This static function creates its instance on the first call
// and returns it's own instance just created
// It only returns its own instance on the later calls
static QPointer<CSuperLog> getInstance(void); //
~CSuperLog();
public slots:
void writingLog(QString aline);
private:
static bool ready;
static bool instanceFlag;
static bool initSuccess;
static QPointer<CSuperLog> ptrInstance;
QTextStream * stream;
QFile * oFile;
QString logFile;
explicit CSuperLog(QObject *parent = 0);
};
I call getInstance() at the beginning of main() so make sure it is read immediately for each other class whenever they need to log important information.
MikeMB:
Your approach is making a middle man sitting in between, it makes the path of the logging info much longer because the signals in Qt are always queued except you make direct connection. The reason why I can't make direct connection here is it make the class non-thread-safe since I use threads in each other classes. Yes, someone will say you can use Mutex, but mutex also creates a queue when more than one thread competing on the same resource. Why don't you use the existing mechanism in Qt instead of making your own?
Thank you all of your posts!
=========================================================
Edit 2:
To Marcel Blanck:
I like your approach as well because you considered resource competition.
Almost in every class, I need signals and slots, so I need QObject, and this is why I choose Qt.
There should be only one instance for one static object, if I didn't get it wrong.
Using semaphores is same as using signals/slots in Qt, both generates message queue.
There always be pros and cons regarding the software design pattern and the application performance. Adding more layers in between makes your code more flexible, but decreases the performance significantly on those lower-configured hardware, making your application depending one most powerful hardware, and that's why most of modern OSes are written in pure C and ASM. How to balance them is really a big challenge.
Could you please explain a little bit more about your static Logger factory approach? Thanks.
I do not like singletons so much because it is always unclean to use them. I have even read job descriptions that say "Knowledge of design patterns while knowing that Singleton isn't one to use". Singleton leads to dependecy hell and if you ever want to change to a completely different logging approach (mabe for testing or production), while not destroying the old one you, need to change a lot.
Another problem with the approch is the usage of signals. Yes get thread savety for free, and do not interrupt the code execution so much but...
Every object you log from needs to be a QObject
If you hunt crashes your last logs will not be printed because the logger had no time to do it before the program crashed.
I would print directly. Maybe you can have a static Logger factory that returns a logger so you can have one logger object in every thread (memory impact will still be very small). Or you have one that is threadsave using semaphores and has a static interface. In both cases the logger should be used via an interface to be more flexible later.
Also make sure that your approach prints directly. Even printf writes to a buffer before being printed and you need to flush it every time or you might never find crashes under bad circumstances, if hunting for them.
Just my 2 cents.
I would consider separating the fact that a logger should be unique, and how the other classes get an instance of the logger class.
Creating and obtaining an instance of the logger could be handled in some sort of factory that internally encapsulates its construction and makes only one instance if need be.
Then, the way that the other classes get an instance of the logger could be handled via Dependency injection or by a static method defined on the aforementioned factory. Using dependency injection, you create the logger first, then inject it into the other classes once created.
A singleton usually has a static function like get_instance() that returns a reference to that singleton, so you don't need to store a pointer to the singleton in every object.
Furthermore it makes no sense, to let each object connect its log signal to the logging slot of the logging object itself, because that makes each and every class in your project dependent on your logging class. Instead, let a class just emit the signal with the log information and establish the connection somewhere central on a higher level (e.g. when setting up your system in the main function). So your other classes don't have to know who is listening (if at all) and you can easily modify or replace your logging class and mechanism.
Btw.: There are already pretty advanced logging libraries out there, so you should find out if you can use one of them or at least, how they are used and adapt that concept to your needs.
==========================
EDIT 1 (response to EDIT 1 of QtFan):
Sorry, apparently I miss understood you because I thought the pointer would be a class member and not only a local variable in the constructor which is of course fine.
Let me also clarify what I meant by making the connection on a higher level:
This was solely aimed at where you make the connection - i.e. where you put the line
connect(gerInstance(), SIGNAL(write(QString)), this, SLOT(write(QString)));
I was suggesting to put this somewhere outside the class e.g. into the main function. So the pseudo code would look something like this:
void main() {
create Thread1
create Thread2
create Thread3
create Logger
connect Thread1 signal to Logger slot
connect Thread2 signal to Logger slot
connect Thread3 signal to Logger slot
run Thread1
run Thread2
run Thread3
}
This has the advantage that your classes don't have to be aware of the kind of logger you are using and whether there is only one or multiple or no one at all. I think the whole idea about signals and slots is that the emitting object doesn't need to know where its signals are processed and the receiving class doesn't have to know where the signals are coming from.
Of course, this is only feasible, if you don't create your objects / threads dynamically during the program's run time. It also doesn't work, if you want to log during the creation of your objects.
I've been trying to create a runnable class in order to interface multi-threaded classes just like java-folks do. But I can't seem to use _beginthread with the virtual function run.
I'm getting the following error:
'beginthread' : cannot convert parameter 1
from 'void (_cdecl Runnable::* )(void *)' to 'void (__cdecl *)(void *)'
#include "CriticalSection.h"
#include <stdio.h>
#include <conio.h>
#include <process.h>
class Runnable{
private:
Runnable() { _beginthread(&Runnable::Run,0,(void*)0); }
~Runnable();
virtual void __cdecl Run ( void* ) = 0;
};
int main(){
//CriticalSection crt;
//ErrorHandler err;
//LockSection lc(&crt,&err);
while(!kbhit());
return 0;
}
There are two approaches to implementing multithreading libraries, both of them used in Java, with slightly different variants for C++. Since you seem to know Java, I will discuss the approaches there:
Deriving from Thread
In this approach, there is a base class that represents a thread, from which you inherit and implement a method that will be called when the thread starts. The base thread class offers control over the thread, and derived classes implement a run (or equivalent) method. The base thread class must not start the actual thread, but let user code start it through a member method start. The reason for this is that if the base thread class started the thread, the newly spawned thread might try to call the overridden method before the full object is created. This has the nasty side effect of calling the overrider in the base thread class in C++, or calling the final overrider of the run method on a yet uninitialized object in Java. --Unsafe in both cases.
Runnable interface
To reduce the possibility of causing undefined behavior, and to separate responsibilities, the second approach distinguishes thread control from the implementation of the code that is to be run in the newly spawned thread. A thread class is created, but not meant to be used as a base class. Rather an interface is offered for Runnable objects. User code will derive from that interface and pass an object to the thread class. The design ensures that the previous error cannot be done, as the Runnable must be fully created before passing it to the thread.
Modern C++ approach to the Runnable interface
The new standard threading libraries (and boost thread) offer an approach similar to the Runnable interface, with a couple of differences. The first is that user code does not need to fullfill a concrete interface but can actually tell the threading library what method of the class is to be run and with what arguments. This is implemented by applying type erasure in the constructor of the thread class, where the exact type of the user arguments are erased for later use inside the thread. This has the same advantages as the Runnable version --ensures that the object is fully created before the thread is spawned. At the same time, it removes the requirement of having to implement an exact interface, which means that you will be able to use a free function, or a member function of a class together with the instance on which that member function is to be called, or a functor that implements operator()...
If you are going to be coding in C++ I recommend that you use the last approach, as that is the most flexible for user code, and at the same time it is safer than what you are trying to do. That is, do not reinvent the wheel, there are good well thought C++ threading libraries (C++11 if you have it, boost if you don't --or Poco, or ACE...) that will avoid many of the pitfalls.
One really important bit to remember is that, whatever the approach you follow, you must ensure that the new thread does not try to call a virtual function in an object that is not fully created, as that will cause Undefined Behavior.
Even if what you wrote compiled as you expected, it wouldn't behave correctly. You are starting a thread in your constructor that will call a pure virtual function on this. But virtual dispatch while constructors are running does not dispatch to classes more derived that the one that is running the constructor.
If that code compiled, you would have a race condition: the virtual call could occur before the constructor of Runnable ended, or while a subclass constructor was running, or after they all ran. Each of these would have a different outcome, and the first one would probably crash.
You need the function to be passed to _beginthread to be static.
I suggest you read this article by Herb Sutter and try to implement the Active Object Pattern.
Use Boost.Thread or C++11 std::thread. Pointers to members are different than ordinary pointers to functions, so you cannot pass them to a C library (they require this pointer to be present, and library cannot handle it, because there is no such thing in C).
I rewriting some code that i written a long time ago.
The code is a class that start another worker thread with AfxBeginThread. When the thread ends, it needs to return it work to the calling class.
Actually when the thread ends it send a message by PostMessage with its results to the called class.
But this way is really dependent of MFC, and to do this my class have to implement all the MFC stuffs.
May be correct if instead of send a message it directly call a non-static method of this class ?
Rather than trying to call a method directly (which will introduce a whole new set of threading problems of its own), try using the native Win32 ::PostMessage() instead of the MFC implementation of the same function. Any thread can call ::PostMessage() to deliver a message to another thread safely.
It sounds as though you want to use regular threading primitives, not window messaging primitives.
Which version of AfxBeginThread are you using? If you pass it a class instance, you should be able to access the members of that class directly once you know its finished running. If you passed it a function pointer, you can pass any class pointer in with the lParam parameter, then use that as a communication context.
You just want to make sure that when you access the class you do it in a thread safe manner. If you wait till the thread has ended you should be fine. Otherwise you could use Critical Sections or Mutexes. See the MSDN article on thread synchronization primitives for more info.
In general, if you have a class that inherits from a Thread class, and you want instances of that class to automatically deallocate after they are finished running, is it okay to delete this?
Specific Example:
In my application I have a Timer class with one static method called schedule. Users call it like so:
Timer::schedule((void*)obj, &callbackFunction, 15); // call callbackFunction(obj) in 15 seconds
The schedule method creates a Task object (which is similar in purpose to a Java TimerTask object). The Task class is private to the Timer class and inherits from the Thread class (which is implemented with pthreads). So the schedule method does this:
Task *task = new Task(obj, callback, seconds);
task->start(); // fork a thread, and call the task's run method
The Task constructor saves the arguments for use in the new thread. In the new thread, the task's run method is called, which looks like this:
void Timer::Task::run() {
Thread::sleep(this->seconds);
this->callback(this->obj);
delete this;
}
Note that I can't make the task object a stack allocated object because the new thread needs it. Also, I've made the Task class private to the Timer class to prevent others from using it.
I am particularly worried because deleting the Task object means deleting the underlying Thread object. The only state in the Thread object is a pthread_t variable. Is there any way this could come back to bite me? Keep in mind that I do not use the pthread_t variable after the run method finishes.
I could bypass calling delete this by introducing some sort of state (either through an argument to the Thread::start method or something in the Thread constructor) signifying that the method that is forked to should delete the object that it is calling the run method on. However, the code seems to work as is.
Any thoughts?
I think the 'delete this' is safe, as long as you don't do anything else afterwards in the run() method (because all of the Task's object's member variables, etc, will be freed memory at that point).
I do wonder about your design though... do you really want to be spawning a new thread every time someone schedules a timer callback? That seems rather inefficient to me. You might look into using a thread pool (or even just a single persistent timer thread, which is really just a thread pool of size one), at least as an optimization for later. (or better yet, implement the timer functionality without spawning extra threads at all... if you're using an event loop with a timeout feature (like select() or WaitForMultipleObjects()) it is possible to multiplex an arbitrary number of independent timer events inside a single thread's event loop)
There's nothing particularly horrible about delete this; as long as you assure that:the object is always dynamically allocated, andno member of the object is ever used after it's deleted.
The first of these is the difficult one. There are steps you can take (e.g. making the ctor private) that help, but nearly anything you do can be bypassed if somebody tries hard enough.
That said, you'd probably be better off with some sort of thread pool. It tends to be more efficient and scalable.
Edit: When I talked about being bypassed, I was thinking of code like this:
class HeapOnly {
private:
HeapOnly () {} // Private Constructor.
~HeapOnly () {} // A Private, non-virtual destructor.
public:
static HeapOnly * instance () { return new HeapOnly(); }
void destroy () { delete this; } // Reclaim memory.
};
That's about as good of protection as we can provide, but getting around it is trivial:
int main() {
char buffer[sizeof(HeapOnly)];
HeapOnly *h = reinterpret_cast<HeapOnly *>(buffer);
h->destroy(); // undefined behavior...
return 0;
}
When it's direct like this, this situation's pretty obvious. When it's spread out over a larger system, with (for example) an object factory actually producing the objects, and code somewhere else entirely allocating the memory, etc., it can become much more difficult to track down.
I originally said "there's nothing particularly horrible about delete this;", and I stand by that -- I'm not going back on that and saying it shouldn't be used. I am trying to warn about the kind of problem that can arise with it if other code "Doesn't play well with others."
delete this frees the memory you have explicitly allocated for the thread to use, but what about the resources allocated by the OS or pthreads library, such as the thread's call stack and kernel thread/process structure (if applicable)? If you never call pthread_join() or pthread_detach() and you never set the detachstate, I think you still have a memory leak.
It also depends on how your Thread class is designed to be used. If it calls pthread_join() in its destructor, that's a problem.
If you use pthread_detach() (which your Thread object might already be doing), and you're careful not to dereference this after deleting this, I think this approach should be workable, but others' suggestions to use a longer-lived thread (or thread pool) are well worth considering.
If all you ever do with a Task object is new it, start it, and then delete it, why would you need an object for it anyway? Why not simply implement a function which does what start does (minus object creation and deletion)?