First up, I'm using the old style signals and slots, and QThreads.
I have two threads, one for the GUI, the other a worker. When a signal is emitted from the worker, the GUI handles this in its own thread.
As part of the process the worker is also passing an object to the slot, so I'm using the following:
self.emit(SIGNAL(my_signal(PyQT_PyObject), self.object_to_pass)
The GUI has to interpret this object; in fact it reads the attributes and updates a progress bar accordingly. The slot is defined as:
def my_slot(self, my_state):
self._state = my_state #so object_to_pass comes in from the worker here
My question is as follows: Is access to the passed object thread safe? What would happen if the worker changed some attribute of the object_to_pass, i.e. would self._state also change?
Access to the passed object is not implicitly thread-safe. Objects are passed through signals by reference, so both threads would be operating on the same object.
Related
Is it possible, to allocate vkCommandPool from the main thread and then move them into a new thread, where it is used exclusively?
Pseudo code:
// Pool for creating secondary buffers
threaded_command_pool = new CommandPool();
// Thread for filling secondary buffers
// threaded_command_poolzd is used only here
thread_handle = new Thread(move(command_pool))
thread_handle.join()
// Pool for merging secondary buffers
command_pool = new CommandPool()
primary_command_buffer = command_pool.create_buffer()
// fill primary_command_buffer with secondary buffers from thread
In all examples and presentation I have found, the command_pool is created in the thread, not in the main thread, but I couldn't find this requirement in the specs.
Nothing in vulkan is bound to a specific thread.
You are free to call any vulkan function from any thread as long as you obey the externally synchronized requirements.
If two commands operate on the same object and at least one of the commands declares the object to be externally synchronized, then the caller must guarantee not only that the commands do not execute simultaneously, but also that the two commands are separated by an appropriate memory barrier (if needed).
In other APIs when an object is bound to a thread it is very clearly documented.
In this case only 1 thread at a time can access a command_pool however successive commands to the same command pool can be from different threads.
I have a unit with an initialization and finalization section. This unit contains a complex object which is instantiated in the initialization and destroyed in the finalization. However, this object also contains an ADO Connection. That makes it an issue when using this across threads, because ADO is COM, and needs to be initialized for every thread.
This is how I currently handle this global object instance:
uses
ActiveX;
...
initialization
CoInitialize(nil);
_MyObject:= TMyObject.Create;
finalization
_MyObject.Free;
CoUninitialize;
end.
This only works on the main thread. Any other thread wouldn't be able to access it, and will return an exception CoInitialize has not been called.
How do I get around this to make this unit thread-safe? I would need a way to hook every creation/destruction of any thread created, and each thread would need to refer to a different instance of this object. But how to go about doing so?
Well, as you already say yourself, each thread needs to call CoInitialize separately. And in addition, each thread needs to have its own ADOConnection too.
I think you need to leave the idea of using the single global object/connection from that unit. Just repeat that object creation and destruction in each thread. When the thread types are different, then you could design a base thread class on top of them. If the object is too big (has overhead with regard to the thread) or does not 'fit' completely in the thread, then split the object design.
For now, your question sounds like just wanting to keep convenience, but if it is really necessary to centralize the ADO connection involvement, then maybe you could implement multi-cast events for the connection events of both main thread and the other threads. Logging in should not be a problem for successive connections: just store the login values and feed them to the threads.
While another design might be a better solution, you can declare _MyObject as threadvar to have a separate instance for each thread. In addition you can move the CoInitialize/CoUnitialize into the constructor/destructor of TMyObject.
I cannot give advice on when to create and free these instances as I have no idea how your threads are created and freed.
I have a form that is responsible for creating and setting up an instance of an object, and then telling the object to go do its work. The process is a long one, so there's an area on the form where status messages appears to let the user know something is happening. Messages are set with a setMessage(string msg) function. To allow the form to remain responsive to events, I create a new thread for the object to run in, and pass it the setMessage function as a delegate to allow the object to set status messages on the form. This part is working properly. The main form is responsive and messages posted to its setMessage function appear as expected.
Because the process is a long one, and is made up of many steps, I want to allow the user to terminate the process before it's finished. To do this I created a volatile bool called _stopRequested and a function called shouldStop() that returns its value. This is also given to the object as a delegate. The object can tell if it should terminate by checking shouldStop() periodically, and if it's true, shut down gracefully.
Lastly, Windows controls are not thread safe, so the compiler will complain if a thread other than the one that created the control tries to manipulate it. Therefore, the setMessage function is wrapped in an if statement that tests for this and invokes the function using the parent thread if it's being called from the worker thread (see http://msdn.microsoft.com/en-us/library/ms171728(v=vs.80).aspx for a description).
The problem arises when the user requests a shutdown. The main form sets _stopRequested to true and then waits for the child thread to finish before closing the application. It does this by executing _child.Join(). Now the parent thread (the one running the form) is in a Join state and can't do anything. The child thread (running the long process) detects the stop flag and attempts to shut down, but before it does, it posts a status message by calling it's setMessage delegate. That delegate points back to the main form, which figures out that the thread setting the message (child) is different than the thread that created the control (parent) and invokes the function in the parent thread. The parent thread is, of course, in a Join state and won't set the text on the text box until the child thread terminates. The child thread won't terminate because it's waiting for the delegate it called to return. Instant deadlock.
I've found examples of signaling a thread to terminate, and I've found examples of child threads sending messages to the parent thread, but I can't find any examples of both things happening at the same time. Can someone give me some pointers on how to avoid this deadlock? Specifically, I'd like the form to wait until the child thread terminates before closing the application but remain able to do work while it waits.
Thanks in advance for the advice.
1-(lazy) Dispatch the method from a new Thread so it doesn't lock
2-(re-think) The main UI thread should be able to control the child thread, so forget the _stopRequested and shouldStop() and implement a childThread.Abort() , abort does not kill the thread, but sends a ThreadAbortException
which can be handled or even canceled
catch(ThreadAbortException e)
{
ReleaseResources();
}
Make the ReleaseResources safe by making various checks such as:
resource != null
or
resource.IsClosed()
The ReleaseResources should be called normally without abort and also by abort.
3-(if possible)stop the child, via main thread call ReleaseResources()
You may have to implement a mix of these.
I have multithread server (inherits QTcpServer). When new connection appears, I create new task (inherits QRunnable), passing socket descriptor to constructor and push this task to QThreadpool (have 3 workers).
QThreadPool::globalInstance()->start(task);
In run() I dynamically create QTcpSocket, set socket descriptor and read first received byte. Based on value of this byte I create new specific task (also inherits QRunnable), passing to its ctr pointer to earlier created QTcpSocket object, and also push this task to QThreadpool.
This specific task make some routine and app crashes.
From log file, I see destructor of this specific task was called.
Also Qt Creator throws next error message:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNativeSocketEngine(0x18c62290), parent's thread is QThread(0x18c603e0), current thread is QThread(0x18cc3b60)
QSocketNotifier: socket notifiers cannot be disabled from another thread
ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 18cc3b60. Receiver '' (of type 'QNativeSocketEngine') was created in thread 18c603e0", file kernel/qcoreapplication.cpp, line 420
I found similar posts but unfortunately I could not understand how to fix my problem.
Please, help me.
You cannot use QTcpSocket from two different threads, because QObjects are not thread-safe.
You've created your QTcpSocket in the first task, so it "lives" in the thread associated with that task. If you pass its pointer into another QRunnable, then a second thread will try to access it, which will break things.
You'll need to redesign your app in a way that doesn't share the same QTcpSocket between different threads. One possibility is to implement different specific functions in your original task, and simply select the appropriate function based on the first received byte
They seem to perform a reasonably similar task: launching a new thread that performs that selector quickly and easily. But are there any differences? Maybe with regards to memory management?
Both are identical.
In iOS and Mac OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
[myObj performSelectorInBackground:#selector(doSomething) withObject:nil];
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads
I presume they are the same, as - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg; is defined in NSThread.h in the NSObject (NSThreadPerformAdditions) category. That is nothing conclusive, but that is evidence in that direction.