Setting Vcl.Clipbrd.Clipboard.AsText content is *thread-safe*, because internally it calls the GlobalAlloc/GlobalUnlock statements in the SetBuffer method. Is it correct?
Setting Vcl.Clipbrd.Clipboard.AsText content is *thread-safe*, because internally it calls the GlobalAlloc/GlobalUnlock statements in the SetBuffer method. Is it correct?
A reference to confirm my assertion: https://stackoverflow.com/a/8422811/133516
ReplyDeleteThe GlobalXXX functions are of course threadsafe. But that's hardly the issue. The real issue is whether or not multiple threads in your processes, or multiple processes try to access the clipboard concurrently.
ReplyDeleteThe OpenClipboard function provides serialisation for that. So the question is which window handle is passed to OpenClipboard. Have a look at the code to find out.
making hard dependency upon implementation details is hiding a landmine for your successors to find.
ReplyDeleteArioch The That's nonsense. Libraries can have contracts. If they don't they are useless.
ReplyDeleteDavid Heffernan the question does mention contract? I don't see it. I see that question is about the function (actually, procedure in Delphi terms) being thread-safe regardless of contract because of "internally it uses GlobalAlloc"
ReplyDeleteArioch The Clearly GlobalAlloc has nothing to do with the question. But it doesn't mean that we can't understand the contract of AsText.
ReplyDeleteDavid Heffernan you could if you discuss the contract, but no one does, you discuss implementation.
ReplyDeleteDavid Heffernan I see from the VCL source code that Application.Handle is passed to the OpenClipboard API, but it's not very clear to me that what does it mean to the *thread safety*?
ReplyDeleteArioch The That makes sense, the VCL's documentation says nothing about the clipboard accessing thread safety, so I'd rather setting the clipboard text in the main thread (which is possible in this specific case in question).
ReplyDeleteEdwin Yip it means that there is no thread safety
ReplyDeleteDavid Heffernan OIC, it means that multiple threads may access the same clipboard handle but has no guarding mechanism applied.
ReplyDeleteThank you all!
Edwin Yip you may also block your program over Clipboard object, but in heavily multithreaded program it can be slow (TMonitor, https://www.delphitools.info/2013/05/30/performance-issue-in-nextgen-arc-model/ )
ReplyDeleteBut if, chances are, your MainVCLThread might sometimes get stuck for long, that would seem a safer option. Maybe even make a thread-safe wrapper like TThreadList vs TList and inject it into Clipboard variable