Fred wrote:theorically, all single commands should work as expected in threadmode, which is not the case with this one, that's why i wondered. About linkedlist, every single commands shouldn't be a problem in threaded mode, but using them in sequence is wrong and can't be really protected.
This is not true. All single command work as long as they do not access a shared
resource.
The only exception here is the access to global floats, longs, words, bytes. (NOT quads and doubles!),
as the access to them is atomic, meaning you can never end up with a
"half-written long value", no matter where the thread execution gets
switched.
A linkedlist (if not protected) is such a shared resource. Modifying the list (AddElement, DeleteElement)
involves changing pointers inside the list, which means there is the possibility
of a race-condition if two threads execute such a command at the same time.
(even if there is no sequence of commands)
(Example: ThreadA reads the Lists *NextElement pointer to execute an AddElement().
Then the thread execution is switched to ThreadB which changes this pointer
by fully executing an AddElement()/DeleteElement().
Now the system switches back to ThreadA who now tries to manipulate the
List with the invalid *NextElement pointer it read before... boom.)
So LinkedList access to a List shared between threads ALWAYS needs a mutex
protection to be save.
Implementing this in the library itself would be too much of a performance hit.
So the rule for the PB commandset is:
With threadsave mode on all the commands are threadsafe as long as they are used
on resources local to the thread. As soon as something shared is used,
there needs to be a protection.
(except for some simpler commands, but its generally better to protect everything)
(Example: ResizeImage() on two images in two threads: no problem.
ResizeImage() on the same image in two threads at once... boom)
The reason there is simple: Every more complex PB command is implemented
as a sequence of actions which, interrupted at the wrong time by another access to the shared resoruce could be problematic.
This is a general problem of thread programming and cannot be solved by
simply mutex protecting every command. This would kill performance and make thread useless
(as the final execution is sequential again as each thread waits for the other)
For the PrintN():
I think the console API is threadsafe (protected by an internal mutex i guess),
but i cannot find any official documentation from MS on this, only rumors
in discussions over the internet.
If this is the case, then we can make the PrintN() threadsafe even without
the need for an additional mutex protection. We just need to change the
command to print everything in a single call (so far it prints the newline separately)
I will research this and see what can be done.