vs2015下pthread的使用

参考:https://blog.csdn.net/k459905889/article/details/48676159

 https://zhuanlan.zhihu.com/p/77551877

目录

一、pthread介绍

二、下载

三、配置

1、解压后共有三个文件夹

2、打开Pre-built.2

3、配置头文件及静态链接库

4、配置动态链接库

四、使用


一、pthread介绍

     POSIX线程(英语:POSIX Threads,常被缩写为Pthreads)是POSIX的线程标准,定义了创建和操纵线程的一套API。实现POSIX 线程标准的库常被称作Pthreads,一般用于Unix-likePOSIX 系统,如Linux、Solaris。但是Microsoft Windows上的实现也存在,例如直接使用Windows API实现的第三方库pthreads-w32;而利用Windows的SFU/SUA子系统,则可以使用微软提供的一部分原生POSIX API。

二、下载

pthread下载:

pthreads-w32-2-9-1

tp://sourceware.org/pub/pthreads-win32/pthreads-w32-2-9-1-release.zip

三、配置

1、解压后共有三个文件夹

Pre-built.2

pthreads.2

QueueUserAPCEx

2、打开Pre-built.2

dll                 ——>动态链接库

include         ——>头文件

lib                 ——>静态链接库

3、配置头文件及静态链接库

把include文件夹中的三个文件直接拷贝到Visual Studio安装目录下VC->include文件夹下,例如我将include中文件拷贝到的位置是

D:\Software\Microsoft Visual Studio 11.0\VC\include

把lib文件夹下的内容拷贝到Visual Studio安装目录下默认的lib寻找路径中,即VC->lib中,例如我将lib文件夹下的x64与x86两个文件直接拷贝到

D:\Software\Microsoft Visual Studio 11.0\VC\lib

4、配置动态链接库

把dll下的x64文件夹下的两个文件,即pthreadGC2.dll与pthreadVC2.dll拷贝到C:\Windows\System32下(64位程序的运行)

把dll下的x86文件夹下的五个文件,拷贝到C:\Windows\SysWOW64下(32位程序的运行)

四、使用


#include "stdafx.h"
#include<iostream>
#define HAVE_STRUCT_TIMESPEC
#include "pthread.h"
#include <windows.h>
 
 
//#include <unistd.h>
 
class Thread {
public:
	Thread();
	~Thread();
	bool Start();
	static void* ThreadFunc(void*);
	bool Run();
private:
	pthread_t mTid;
};
 
 
 
Thread::Thread() 
{
 
}
 
Thread::~Thread() {
 
}
 
bool Thread::Start() {
	return 0 == pthread_create(&mTid, NULL, &Thread::ThreadFunc, (void*)this);
}
 
void* Thread::ThreadFunc(void* arg) {
	Thread* self = (Thread*)arg;
	self->Run();
	return NULL;
}
 
bool Thread::Run() {
	while (true) {
		std::cout << mTid.p << std::endl;
		Sleep(1);
	}
 
	return true;
}
 
int main() {
	Thread t1;
	t1.Start();
	Thread t2;
	t2.Start();
	Thread t3;
	t3.Start();
 
	while (true) {
		
		Sleep(1);
	}
 
}

         上述代码中,Thread类提供类3个函数,其中Start()为入口,调用pthreadcreate,而关键点就在这里了。pthread_create的第三个参数,也就是线程调用的函数传了一个Thread类的静态函数进去,因为在类中,静态成员函数是不需要通过类的访问的,所以pthread_create能够直接调用这个函数。而最关键的点就在于第四个参数,这里把this指针给传进去了,为什么呢?大家可以看到,在ThreadFunc函数的实现中,我们会把本身为void*类型的this指针重新强制类型转换为Thread* 类型,然后用来调用Run()方法。由于this指针就是类实例本身,通过这样两次类型的转换,线程和对应的类实例就绑定起来了。

猜你喜欢

转载自blog.csdn.net/kupe87826/article/details/108196801