Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Thread-safe? What & How?

Status
Not open for further replies.

inetd

Technical User
Jan 23, 2002
115
HK
What is the exact meaning of thread-safe?

And, how do I know my code is thread-safe and how to write the thread-safe code?

Thx.
 
Threads operate with the same variables as the main task.

Subsequently, while both are running *simultaneously* (watch how you take that stmt without multiple cpu(s)) you can "use" variables in both/multiple threads and thus *screw* yourself.

Thread-safe means you have taken measures to *not* fall into that trap.

As for myself, I generally run a thread kind of like a program. I define some input "parm" variables, define some for just the thread (those that can't be put on the stack), and a place for the "response" (more variables).

I don't know if it's *eloquent* or not, but it works.




Regards and HTH,
JGS
 
JGS is on the money, but I'll add my two cents.

Non-thread-safe code may consist of two threads (one of which may be the main program thread), and where they *can* both update a variable (ie. loop := loop + 1). The variable would obviously have to be visible to both, and for simplicity lets assume in a global variable declared in a common unit.

The issue arises when the both may be attempting to modify the variable at the same time which can cause no end of problems. Delphi has a few mechanisms to prevent this. The help file has a lot of good info on learning how to use threads properly. Also, consult for heaps of information on the topic. That's chapter 8 of an excellent website (contents page link at the bottom). I recommend slogging through it all.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top