1

Noob question:

This link shows an example of CreateEvent and CreateThread

http://msdn.microsoft.com/en-us/library/ms686915(v=vs.85).aspx

My question is if the ThreadProc is truly thread safe?

Specifically, the dwWaitResult variable. Since all threads are waiting on the same event, it turns out this code works but had different events been created, for example, this would not work correct?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Eric
  • 1,697
  • 5
  • 29
  • 39

2 Answers2

3

The dwWaitResult variable is a local variable in that function. Thus each individual thread has its own copy, which assures that the variable is thread safe. Each thread has its own stack, therefore all local variables are specific to the individual thread.

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
  • "therefore all local variables are specific to the individual thread." Is it true that because the variable is local & non-static that each caller (thread) has a separate instantiation of the variable dwWaitResult? – Eric Jan 11 '11 at 15:26
  • @Eric M, Yes. If the variable was marked as static in the function, then it would be shared among all instances. – Mark Wilkins Jan 11 '11 at 15:35
0

The Event is created by name, so if the event is already created is reused in any other thread "creating" an event with the same name. As a result, the example code IS thread safe.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115