4

i.e. when I start a new thread, is it safe to read any variables initialized before the thread start from the newly started thread?

UPD why I'm asking? Because some developers assume that it does have, and don't use any explicit memory barriers there. And I couldn't reproduce any bugs in that code. However, documentation http://msdn.microsoft.com/en-us/library/ms686355(v=vs.85).aspx doesn't say this is safe.

user626528
  • 13,999
  • 30
  • 78
  • 146
  • 1
    Nothing special about a new thread starting. You need to take the same precautions as if it was an already executing thread. Note that your link discusses native code rather than managed code. – David Heffernan May 20 '12 at 10:10

1 Answers1

5

Yes, the operating system provides the implicit barrier. It can't get the thread started without taking an internal lock that protects the thread scheduler data structures.

Which isn't explicitly promised that I know of. Since .NET 2.0, there is no longer a direct correspondence between a Thread and a ProcessThread. This link was broken at the request of the SQL Server team that wanted to implement a Thread with a fiber. This did not actually happen, they gave up on the project when they couldn't make it reliable enough. Given the outcome of this project and no mainstream project I know of that has ever tried to take advantage of this again, as well as the difficulty of implementing Thread support that doesn't use a lock, I'd say it is safe to assume you can rely on the implicit barrier.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536