在VS2010中配置pthread

1下载win32下的pthread库
    Windows本身没有提供对POSIX的支持。但有一个叫 POSIX Threads for Win32 的开源项目给出了一个功能比较完善的Windows下pthreads API的实现。访问ftp://sourceware.org/pub/pthreads-win32/dll-latest 下载 可用的 pthread.h  sched.h semaphore.h -----  pthreadVC2.lib  -----  pthreadVC2.dll .h  .lib  .Dll文件)。

 

2 vc2010开发环境的设置
    添加执行库、目录、库文件的路径;
a、目录

     PROJECT->项目名->property Pages->VC++Directories中设置头文件和lib库引用目录  如下:


 

b、库文件pthreadVC2.lib
PROJECT->项目名->property Pages->Linker->Input中设置依赖的lib库文件

(注:也可用#pragma comment(lib, "pthreadVC2.lib")代替

 

 

c、动态库文件pthreadVC2.dll
    pthreadVC2.dll拷贝到c:/windows/system32文件夹下  针对某个项目放置在该项目的Debug文件中

 

3 测试

    编写程序,添加项目中库文件,编译运行即可。

//创建10个线程 并在线程间传递数据

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <windows.h>

#include <iostream>

using namespace std;

pthread_mutex_t  mut = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t  con = PTHREAD_COND_INITIALIZER;


int ret;

void* print(void* pval)

{

    pthread_mutex_lock(&mut);

    int* i = static_cast<int*>(pval);

    cout<<"i = "<< (*i)++ << endl;

    pthread_cond_signal(&con);

    pthread_mutex_unlock(&mut);

    return NULL;

}

int main()

{

    pthread_t thr[10];;

    int i = 0;

    while(i < 10)

    {

        cout << "while i = "<< i<<endl;

        pthread_mutex_lock(&mut);

        pthread_create(&thr[i],NULL,print,&i);

        pthread_cond_wait(&con, &mut);

        pthread_mutex_unlock(&mut);

    }

    for (int i = 0 ;i < 10 ;i++)

    {

        pthread_join(thr[i],NULL);

    }

    return 0;

}



猜你喜欢

转载自blog.csdn.net/u012278016/article/details/79930532