dose the emit self is thread safe?
-
i have a global object ,and it have one signal, and i send this signal in two worker thread . dose the emit is thread safe?
one is :
QtConcurrent::run(this{
char databuff[255]={0};
emit this->signalforsomething(databuff);
});
another is same :
QtConcurrent::run(this{
char databuff[255]={0};
emit this->signalforsomething(databuff);
}); -
QMetaObject::activate
looks to be thread safe so it should be ok. An alternative would be to use 2 separate proxy objects, connect their signals to the global object signal and emit the signals from the proxys.emit
will return immediately sodatabuff
will go out of scope before the slots can use it. It's easily solved by usingQByteArray
instead of a rawchar []
-
It's easily solved by using QByteArray instead of a raw char []
Ah, I certainly did not know that! I presume it's because
QByteArray
hasQ_OBJECT
or something? Could you point me to docs which explain the persistence of whatever Qt types instead of the C++ ones across signals/slots so that I can at least read up? My situation is different because I use Python/PyQt, but I'd like to understand how it works from C++. Thanks. -
@JonB said in dose the emit self is thread safe?:
but I'd like to understand how it works from C++
This is very C++ centric. raw arrays passed to a function are not copied, they just get passed as pointers to the original memory so if the original memory is destroyed the pointer becomes meaningless.
Any declared and registered metatype with a copy constructor can be passed by value or const reference to a signal without any overhead.
I suggested
QByteArray
as it's the container version Qt offers forchar[]
butstd::array<char,255>
would work as well once you register it with the meta object system -
yes i am mistake, char databuff[255]={0}; this should be QByteArray ..fix:
one is :
QtConcurrent::run(this{
QByteArray databuff1= "xxx";
emit this->signalforsomething(databuff1);
});
another is same :
QtConcurrent::run(this{
QByteArray databuff2= "yyyy";
emit this->signalforsomething(databuff2);
});
btw ,the two connects is Qt::QueuedConnection;; for easy to manage. i use a global object to manage all the singnal of my app. and i wonder if the emit itself is thread-safe in diffrent worker thread ..and my result of test looks no problem as VRonin saying. but i still worry about it that it may have a small chance of working wrong -
@jimfar said in dose the emit self is thread safe?:
i use a global object to manage all the singnal of my app
Bad idea.
which doc of qt i can found to described this detail?
I don't think it's documented, you just have to trust QMetaObject::activate to remain thread safe
-