Windows thread with C++

Windows thread with C++

本文关键字:C++ with thread Windows      更新时间:2023-10-16

我看到这个c++线程的简单例子但我的问题是,我想在windows 32中运行这个程序,似乎pthread在windows中不被识别!请告诉我有什么问题?这是我的错误:致命错误C1010:查找预编译头文件时意外结束文件。您是否忘记在源代码中添加"#include"StdAfx.h ?(我添加了#include"StdAfx.h",但它仍然不工作!)

#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 %ldn", t);
  rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
  if (rc){
        printf("ERROR; return code from pthread_create() is %dn", rc);
        exit(-1);
         }
  }
   /* Last thing that main() should do */
   pthread_exit(NULL);
   }

因为线程是与体系结构相关的概念,如果不使用某种包装器或使用特定于windows的线程函数,您将无法使用pthread。

你有三个选择

  1. 使用pthread-win32 (Win32线程函数的包装:http://sourceware.org/pthreads-win32/)
  2. 使用Windows特定的线程函数,#ifdef _WIN32 #else #endif环绕
  3. 使用boost线程库

编辑:对于C1010错误遵循上述答案

根据你的编译错误:

致命错误C1010:查找文件时意外结束预编译头。你忘记添加"#include"StdAfx.h"了吗你的来源吗?

…这个问题与pthread无关。它与预编译头文件有关。

  1. 在项目中关闭使用预编译头文件。项目>设置> C/c++>预编译头文件
  2. 按照错误提示,在CPP文件
  3. 中添加#include "stdafx.h"作为第一行