【问题标题】:Cannot get the threads to work in C++?无法让线程在 C++ 中工作?
【发布时间】:2014-05-03 23:50:43
【问题描述】:

我正在尝试创建一个使用 PrintHello 方法创建五个简单线程的程序。我希望能够运行该程序并查看线程将如何工作以及何时打印出来。我知道一个线程在任务之间划分时间。因此,一个任务可能运行 1 秒,而另一个任务可能只运行 0.01 秒,但它给人一种所有程序同时运行的错觉。

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

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

for 循环遍历数组的长度。 for(i=0;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

【问题讨论】:

  • 很明显 - 它找不到 pthread.h。试试#include &lt;pthread.h&gt;
  • 您在 devstudio 中执行此操作,这意味着您没有正确地将 pthread windows shim 包含到您的项目中(windows 本身并不公开 pthreads)。你可以修复#include,甚至可以让它工作,但我会直接告诉你,如果你可以使用VS2012或更高版本,放弃all并使用C++11 &lt;thread&gt; support library . (顺便说一句,您没有加入任何已启动的线程,这可能是一个错误)。
  • 我正在使用 Visual C++ Visual Studio 2010。
  • #include

标签: c++


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多