views:

167

answers:

4

What do I need and how can I use threads in C on Windows Vista?

Could you please give me a simple code example?

+5  A: 

Here is the MSDN sample on how to use CreateThread() on Windows.

The basic idea is you call CreateThread() and pass it a pointer to your thread function, which is what will be run on the target thread once it is created.

The simplest code to do it is:

#include <windows.h>

DWORD WINAPI ThreadFunc(void* data) {
  // Do stuff.  This will be the first funciton called on the new thread.
  // When this function returns, the thread goes away.  See MSDN for more details.
  return 0;
}

int main() {
  HANDLE thread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
  if (thread) {
    // Optionally do stuff, such as wait on the thread.
  }
}

You also have the option of calling SHCreateThread()—same basic idea but will do some shell-type initialization for you if you ask it, such as initializing COM, etc.

jeffamaphone
Keep in mind, however, that if you're going to use the CRT in the new thread you may need to be extremely careful.In MSVC, for example, you should use _beginthread/_beginthreadex and _endthread instead of the relative APIs, to let the CRT correctly allocate/deallocate its internal per-thread structures. I think that also in other CRTs it should go somehow like that.
Matteo Italia
A: 

Take a look at MSDN.

Pablo Santa Cruz
+2  A: 

You would use the CreateThread function.

You mentioned semaphores as well. For that you would use CreateSemaphore.

A: 

Atomic operations and mutexes are good. I use CreateThread etc, not pthreads.

martinr