1.下载pthread 的windows安装包
可以从官方网站上下载,网址:http://sourceware.org/pthreads-win32
也可以下载我上传的资源,以下将以我上传的资源来讲解。(下载)
如下图:
2.配置VS2017
打开vs2017,项目->属性->配置属性->VC++目录,包含目录里添加inlude路径;在库目录那一栏添加lib路径
添加库目录的时候,根据自己的系统选择;32为选择x86;64位选择x64
在链接器—>输入,附加依赖项一栏添加 pthreadVC2.lib如下图所示。所有设置完成后点确定
这样就设置好了,大功告成。可以创建项目测试
#include "stdafx.h"
#include <iostream>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
// 线程的运行函数
void* say_hello(void* args)
{
cout << "Hello Runoob!" << endl;
return 0;
}
void threadTest(void)
{
// 定义线程的 id 变量,多个变量使用数组
pthread_t tids[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i)
{
//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
if (ret != 0)
{
cout << "pthread_create error: error_code=" << ret << endl;
}
}
//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
pthread_exit(NULL);
}
如果 pthread.h中报错:C2011 “timespec”:“struct”类型重定义
解决方法:
在
#if !defined( PTHREAD_H )
#define PTHREAD_H
下面加上
#define HAVE_STRUCT_TIMESPEC