C++ 中使用pthread.h头文件的方法
下载 pthreads-w32-2-7-0-release.exe, 链接: https://pan.baidu.com/s/137XgDd2cr2qii3Phli7u2Q 提取码: yx55
下载后运行会解压生成三个文件夹 Pre-built.2、pthreads.2、QueueUserAPCEx
打开Pre-built.2文件夹,分别复制include文件夹和lib文件夹中的文件到
VS安装目录下的\VC\include文件夹和\VC\lib文件夹中 或者
VC6.0安装目录下的\VC98\include文件夹和\VC 98\lib文件夹中
包含头文件pthread.h后,运行可能会提示错误
错误 1 error LNK2019: 无法解析的外部符号 __imp__pthread_create,该符号在函数 _main 中被引用
此时需要在代码中加入
#pragma comment(lib, "pthreadVC2.lib")
运行即可通过。
pthread.h头文件简单使用:
#include <iostream>
#include <pthread.h>
using namespace std;
#pragma comment(lib, "pthreadVC2.lib")
void * thread(void * a)
{
for (int i = 0; i < 30; i++)
{
printf("线程执行第 %d 次\n", i+1);
}
return NULL;
}
void main()
{
pthread_t id;
int ret = pthread_create(&id,NULL, thread, NULL);
if (ret != 0)
{
cout << "线程创建错误!" << endl;
exit(-1);
}
for (int i = 0; i < 30; i++)
{
printf("main函数执行第 %d 次\n", i+1);
}
pthread_join(id, NULL);
}