无法让线程在C ++中工作?

时间:2014-03-25 21:15:28

标签: c++

我正在尝试使用PrintHello方法创建一个使用五个简单线程的程序。我希望能够运行这个程序,看看线程将如何工作以及何时打印出来。我知道一个线程在任务之间分配时间。因此,任务可能会运行1秒,而其他任务可能只会运行.01秒,但它会让人觉得所有程序都在同时运行。

我希望我的程序能够演示一个线程如何工作,并希望它能够将线程数改为多于或少于5个。

第一行创建一个线程数组。       pthread_t个线程[NUM_THREADS];

for循环遍历数组的长度。       for(i = 0; i< NUM_THREADS; i ++){          ...       }

这行代码将创建线程:       pthread_create(& threads [i],NULL,PrintHello,(void *)i);

这将退出主题。       了pthread_exit(NULL);

我收到的错误列在此窗口的底部。

代码:

#include "pthread.h"
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}

int _tmain(int argc, _TCHAR* argv[])
{
    pthread_t threads[NUM_THREADS];
    int rc;
    int i;
    for( i=0; i < NUM_THREADS; i++ ){
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)i);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
    std::getchar();
    return 0;
}

错误:

Error   1   error C1083: Cannot open include file: 'pthread.h': No such file or directory   c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp  6   1   TestProject
    2   IntelliSense: cannot open source file "pthread.h"   c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp  6   1   TestProject
    3   IntelliSense: identifier "pthread_exit" is undefined    c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp  79  4   TestProject
    4   IntelliSense: identifier "pthread_t" is undefined   c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp  84  2   TestProject
    5   IntelliSense: identifier "pthread_create" is undefined  c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp  89  12  TestProject
    6   IntelliSense: identifier "pthread_exit" is undefined    c:\users\itpr13266\desktop\c++\testproject\testproject\testproject.cpp  96  4   TestProject

1 个答案:

答案 0 :(得分:1)

据我了解,Visual Studio不了解pthreads。 因此,您应该在项目中包含pthreads库。

以下是我在google中找到的第一个链接:

http://linqtolinq.wordpress.com/2012/04/24/setting-up-pthreads-in-windows-under-visual-studio/