0

I saw this question Simple example of threading in C++ but my problem is that I want to run this program in windows 32 and it seems that pthread is not recognized in windows!please tell me what is problem?This is my error: fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?(I added #include "StdAfx.h but it still does not work!)

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
  long tid;
  tid = (long)threadid;
  printf("Hello World! It's me, thread #%ld!\n", tid);
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  pthread_t threads[NUM_THREADS];
  int rc;
  long t;
  for(t=0;t<NUM_THREADS;t++)
  {
  printf("In main: creating thread %ld\n", t);
  rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
  if (rc){
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
         }
  }

   /* Last thing that main() should do */
   pthread_exit(NULL);
   }
Community
  • 1
  • 1
Sara
  • 2,308
  • 11
  • 50
  • 76
  • I added #include "StdAfx.h" but still it does not recognized pthread! – Sara Oct 26 '11 at 21:35
  • What's the error now you've included "StdAfx.h"? – ChrisF Oct 26 '11 at 21:37
  • Possible duplicate - http://stackoverflow.com/questions/4170038/using-pthread-h-on-a-windows-build – ChrisF Oct 26 '11 at 21:38
  • fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source? – Sara Oct 26 '11 at 21:40
  • and the other is fatal error C1083: Cannot open include file: 'pthread.h': No such file or directory – Sara Oct 26 '11 at 21:41

2 Answers2

3

Because threads are architecture dependent concept, you won't be able to use pthread without using some kind of a wrapper or use windows-specific threading functions.

You have three choices

  1. Use pthread-win32 (wrapper for Win32 thread functions :http://sourceware.org/pthreads-win32/ )
  2. Use Windows specific threading functions with #ifdef _WIN32 #else #endif wrapped around
  3. Use boost thread library

EDIT: for C1010 error follow the above answer.

JosephH
  • 8,465
  • 4
  • 34
  • 62
2

According to your compiler error:

fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?

...the problem has nothing to do with pthreads. It has to do with precompiled header files.

You can either:

  1. Turn off using precompiled header files in your project. Project>Settings>C/C++>Precompiled Headers
  2. Do as the error suggests, and add #include "stdafx.h" as the first line in the CPP file
John Dibling
  • 99,718
  • 31
  • 186
  • 324