win32+VS2013下使用pthread

来源:互联网 发布:怎么卸载java 编辑:程序博客网 时间:2024/04/30 19:18


POSIX Threads for Win32项目,专门为win32开发了一个pthread的lib,利用这个项目可以很方便的在win32下实现pthread的应用。

一,下载

POSIX Threads for Win32目前可以下载到的最新版本是2.9.1 ,

下载地址:https://sourceforge.net/projects/pthreads4w/files/?source=navbar

将下载到的zip解压之后,会得到三个目录:其中,Pre-built.2中是已经编译好的lib以及dll,同时包含了一些必要的头文件。

二 .配置

将其中的include文件夹和lib文件夹 copy到VC的安装目录下,例如,我的是vs2013的环境,默认安装,则,

需要copy到:Program Files (x86)\Microsoft Visual Studio 12.0\VC

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

把dll下的x86文件夹下的五个文件,拷贝到C:\Windows\SysWOW64下(用于32位程序的运行),注意一下,千万不能将这些文件拷贝反位置,否则,程序运行时会提示说找不到对应的dll文件。


三.使用

   在编程的时候,引入pthreadVC2.lib即可:

    #pragma comment(lib, "pthreadVC2.lib")

调试个例子,(代码来自网络)

#include <stdio.h>  #include <pthread.h>  #include <assert.h>  #pragma comment(lib, "pthreadVC2.lib")typedef struct _qsort_parm{ int *array;     int low;     int high; } qsort_parm_t;/*分段*/int partition(int *array, int low, int high){int pivot = *(array + low); //first elementwhile (low < high){while (low < high && array[high] >= pivot){high--;}*(array + low) = *(array + high);while (low < high && array[low] <= pivot){low++;}*(array + high) = *(array + low);}*(array + low) = pivot;return low;}/*线程执行函数*/void* quicksort_worker(void *parm){pthread_t corpid;qsort_parm_t *iparm = (qsort_parm_t *)parm;int keypos = 0;qsort_parm_t qparm;void *ret;if (iparm->low < iparm->high){/*分段*/keypos = partition(iparm->array, iparm->low, iparm->high);qparm.array = iparm->array;qparm.low = iparm->low;qparm.high = keypos - 1;/*创建子线程处理前半段*/pthread_create(&corpid, NULL, quicksort_worker, &qparm);iparm->low = keypos + 1;/*本线程处理后半段*/quicksort_worker(iparm);/*等待子线程结束*/pthread_join(corpid, &ret);}return NULL;}void* Function_t(void* Param){printf("我是线程! ");pthread_t myid = pthread_self();printf("线程ID=%d ", myid);return NULL;}void quicksort_multithread(int *pA, int low, int high){ qsort_parm_t qparm;    qparm.array = pA;    qparm.low = low;    qparm.high = high;    quicksort_worker(&qparm); }int main(void){ int array[20] = { 9, 8, 0, 1, 4, 7, 6, 2, 3, 5, 19, 11, 18, 16, 10, 22, 38, 45, 14, 21 };   int i = 0;    quicksort_multithread(array, 0, 19);   for (i = 0; i < 20; i++)    { printf("%d ", array[i]); }   getchar();return 0;}

0 0
原创粉丝点击