Posts

Showing posts with the label Multithreading

Assigning result to a function from asynchronous code

One of the more common problems that comes up in multi-threading, especially when refactoring existing code, is assigning a result obtained from asynchronous code. In other words, how do you write a function that will return some value, and calculate that value in a background thread? Basically, converting the following code: function GetData(...): string; var Data: string; begin Data := LongTask(...); // assign result of a long-running task to a function Result := Data; end; To this one: function GetData(...): string; var Data: string; begin TThread.CreateAnonymousThread( procedure begin Data := LongTask(...); end).Start; // assign result of a long-running task to a function Result := Data; end; Now, the above code will compile, but it will not achieve the desired functionality. Even if we ignore its thread safety issues (the background thread writes to the Data variable and that can interfere with assigning it to the function result), the funct...

CodeRage 2022: Challenges of Multi-threaded Programming

Image
Here you can find slides from my CodeRage 2022 presentation about Challenges of Multi-threaded Programming , as well as additional links to code examples related to the presentation. Slides: https://dalija.prasnikar.info/dl/DP_CodeRage2022.pdf Additional links: Thread-safe Event Bus: https://github.com/dalijap/nx-horizon Books: Delphi Event-based and Asynchronous Programming: Code Examples: https://github.com/dalijap/code-delphi-async Book: https://dalija.prasnikar.info/delphiebap/ Delphi Thread Safety Patterns: Code Examples: https://github.com/dalijap/code-delphi-thread-safety Book: https://dalija.prasnikar.info/delphitspatt/ Delphi Memory Management: Code Examples: https://github.com/dalijap/code-delphi-mm Book: https://dalija.prasnikar.info/delphimm/ Replay of the presentation can be found at:  https://www.youtube.com/watch?v=d4QTRXVj8mg

Delphi Thread Safety Patterns book available on Amazon

Image
Delphi Thread Safety Patterns book is now available as paperback on Amazon, too.  https://dalija.prasnikar.info/delphitspatt/ While the thread safety of a particular piece of code depends on the surrounding context and how it is used, some data types are inherently unsafe, and for some of them, thread safety will depend on the use case and the specific code. Unfortunately, when you look at some class, type declaration, or API in isolation, there is very little information there that will tell you whether instances of that type can be safely used in multiple threads, or under which conditions. The proper place to learn about the thread safety of an API is its documentation. However, most documentation will not explicitly give you that information. Occasionally, the documentation will mention that a particular feature is not thread-safe, or will tell you that a feature can be used in background threads, but for the most part, you will have to figure out thread safety on your own. One...

FreeAndNil Debate: Thread Safety

One of the topics raised in yesterday's FreeAndNil debate was using FreeAndNil in multi-threaded code for avoiding access to a dangling reference when multiple threads are accessing and using the same object instance. Problem is that FreeAndNil is not thread-safe and cannot be used to achieve thread safety. You cannot call FreeAndNil on a shared object reference in one thread and then use if Assigned  in another to check whether object is still alive and then do something with that object. Your second thread can pass the if Assigned check and start working with the object while the first thread can destroy that object at any point. There is no mechanism in the FreeAndNil and if Assigned check that can prevent that. If you need to use shared object instance in such manner you need to use locking mechanism and lock all access, in all threads, to such an object. If you use locking mechanism, then you can use FreeAndNil in one thread and if Assigned check in another. I ment...

Anonymous Threads: Use or Lose?

Anonymous threads are simple to use and are highly appealing when you need to quickly put and execute some small piece of code in a background thread. They work great when they run and complete, but if you have such a thread running when you close the application, all hell can break loose. The main cause of trouble with anonymous threads is self-destruction on completion. Because of that you cannot store a reference to such a thread and therefore you cannot wait for its completion during application shutdown. Other custom threads which have the FreeOnTerminate flag set to True also suffer from the same problem. During application shutdown, such self-destroying threads will keep running until they are just killed by the OS, because their owning process exited. This means they can be interrupted at any point during their execution, and they can access shared data long after that data has been destroyed during shutdown. If you want to avoid unexpected behavior and crashes during app...

Just released book: Delphi Thread Safety Patterns

Image
Delphi Thread Safety Patterns Book https://dalija.prasnikar.info/delphitspatt/ While the thread safety of a particular piece of code depends on the surrounding context and how it is used, some data types are inherently unsafe, and for some of them, thread safety will depend on the use case and the specific code. Unfortunately, when you look at some class, type declaration, or API in isolation, there is very little information there that will tell you whether instances of that type can be safely used in multiple threads, or under which conditions. The proper place to learn about the thread safety of an API is its documentation. However, most documentation will not explicitly give you that information. Occasionally, the documentation will mention that a particular feature is not thread-safe, or will tell you that a feature can be used in background threads, but for the most part, you will have to figure out thread safety on your own. One reason for this is that thread safety depends on t...

Overprotecting multithreaded code

Running long tasks in a background thread to keep the UI responsive is one of the main purposes of multithreading. A common code pattern for doing so would look like: procedure TMainForm.BtnClick(Sender: TObject); begin TThread.CreateAnonymousThread( procedure begin DoSomeWork; end; end).Start; end; However, such code often needs to show the results of that long work to the user. Working with the GUI from a background thread is not thread-safe, so such code should be executed in the context of the main thread: procedure TMainForm.BtnClick(Sender: TObject); begin TThread.CreateAnonymousThread( procedure begin DoSomeWork; TThread.Synchronize(nil, procedure begin ShowResults; end); end; end).Start; end; Because ShowResults will run in the context of the main thread, the code in ShowResults should be as minimal as possible—read: as fast as possible. Once you enter into the Synchronize (or Que...

Delphi Event-based and Asynchronous Programming Book - Paperback Edition and Invitation to Webinar

Image
 You asked for it, and here it is!  The paperback version of the book is here! (I hope Gaia will forgive me again...) Celebrating the release of the new book, “Delphi Event-based and Asynchronous Programming,” Jim McKeeth and I will have a chat about it during a webinar featuring a Q&A where I'll be answering your questions. Let's not reinvent the wheel here... here's the intro Jim McKeeth wrote: Join Embarcadero MVP Dalija Prasnikar and Jim McKeeth for this fireside chat about Event-Based and Asynchronous Programming in Delphi. This is your chance to get answers to your questions on the topic. Register for the webinar here: https://register.gotowebinar.com/register/9060745883744641039 Learn even more from Dalija’s recently published 291-page book: “Delphi Event-based and Asynchronous Programming,” and score a 50% discount on the physical book if you purchase the ebook!  If you have already purchased the eBook version, and wish to buy the paperback, you're also elig...

Just released: Delphi Event-based and Asynchronous Programming - Complete version - 291 Pages

Image
 Delphi Event-based and Asynchronous Programming https://dalija.prasnikar.info/delphiebap/index.html Event-based programming is everywhere. Nowadays, you can hardly write any kind of application without leaning on events and messages. This simple, yet extremely powerful mechanism is also the cornerstone of asynchronous and multithreaded programming. Without events, we would not know when some task was completed. But, asynchronous and multithreaded programming consists of more than just handling multiple threads, protecting shared resources, and synchronization. It also includes designing and understanding program flow. That design aspect is often forgotten, taken for granted, and solving all the fine-grained nuances of multithreaded programming hogs the spotlight. Without understanding asynchronous flow and the bigger picture it can be hard to properly solve all the other issues, including multithreading. What used to be plain spaghetti code, now becomes temporal spaghetti. You can...

You already purchased Delphi Event-based and Asynchronous Programming Part I?

Image
Thanks to all of you who purchased the incomplete pre-release version (179 pages) of my eBook! After a minor delay, the full version is here! You can download it through the same PDF/epub/mobi links that you have received earlier from FastSpring via email. The subject line of that email message was: "Your Delphi Event-based and Asynchronous Programming - Part I Delivery Information". If you have any problems, feel free to contact me via the contact form on my site. Thanks again! Happy Holidays to you all! 

Just released eBook: Delphi Event-based and Asynchronous Programming

Image
 Delphi Event-based and Asynchronous Programming  I just had to do it... Go with the flow! It's the Black Friday / Cyber Monday "season", so I had to rush the book offer  The book was actually scheduled for release in early December, but then the Black Friday deals started popping up all over the place... pressure was building... and I finally caved in! I cut the darn thing in two, and decided to offer Part I at a discount, and will give Part II for free to all Buyers. Not really a 97% BF discount but hey... Junior is still studying, and we still have to pay the bills (Corona doesn't help, either)! So, here it is!  I hope you'll like it like you did Delphi Memory Management! https://dalija.prasnikar.info/delphiebap/index.html Event-based programming is everywhere. Nowadays, you can hardly write any kind of application without leaning on events and messages. This simple, yet extremely powerful mechanism is also the cornerstone of asynchronous and multithreaded prog...

New Book In The Press!

Image
 Delphi Event-based and Asynchronous Programming  About to be released by the end of the month, Delphi Event-based and Asynchronous Programming brings you the following in about 260 pages: Event loops Messaging systems Asynchronous programming Removing Application.ProcessMessages and moving tasks to background threads Threads in general Tasks Futures Thread safety Communicating with the GUI And more... Stay tuned  Just released eBook: Delphi Event-based and Asynchronous Programming

What is thread safety anyway?

Multithreading can be hard to do right. The most common point of failure is assuming some code is thread safe when it actually is not. And then the whole multithreading castle crumbles into ruins. "Thread safe" is a pretty vague term. If you are not sure what it actually means, I suggest you start by reading Eric Lippert's blog post on the subject. On the other hand, if you do know what thread safety is, well, I suggest you read it anyway  🙂 What is this thing you call "thread safe"? Wrong assumptions When it comes to thread safety in Delphi (actually, this is not a Delphi-specific thing) there is very little built in by default. Basically, if you are writing some code that has to be thread safe, you have to take care of the thread safety part all by yourself. And you have to be very careful with your assumptions, as you can easily come to the wrong conclusions. To demonstrate how deeply unsafety goes, and how easy is to make wrong assumptions, I ...