I have been trying to learn about threads via the Windows API. I ran across __declspec( thread ) from msdn, but I don’t understand what the difference is between that and CreateThread().
It sounds like you only create the thread on the object? Does that mean that if I wrote a method that does while(1); and ran that method in my main class through that object, it would do that in a separate thread? I guess my question is what is __declspec ( thread ) used for, and should I use that over CreateThread?
Sorry if my question is confusing.
The difference between them is huge:
__declspec( thread )is a storage modifier that specifies that the declared variable has local storage. That means that each thread owns its own copy of this value. Is the threaded version of globals.C++11 introduces thread storage modifiers by the name
thread_local. Its a storage modifier, likestatic.CreateThread()is a function that will create a new thread and start running some function you specify.C++11 also introduces an entire threading API that you can use to write thread-aware code that will run on (almost) any platform. You can search for
std::threadandstd::async…So basically they are two entirely different things, used for entirely different purposes. If you want to create a new thread using the Windows API then use
CreateThread. If you want a variable to havethread_localstorage using the Windows API then use__declspec( thread ). If you can use C++11, you should forget about the subtleties of the Windows API and use the Standard API instead.