Windows平台下使用pthreads开发多线程应用

pthreads简介

POSIX 1003.1-2001标准定义了编写多线程应用程序的API(应用程序编程接口),这个接口一般被称为pthreads。在常见的操做系统中,例如Unix、Linux、MacOS等都使用pthreads做为操做系统的线程。
Windows操做系统和其余平台不一样,并非与生俱来的就支持phreads,使用Win32或MFC编写过应用程序的朋友应该都知道,Windows平台能够经过系统对外提供的线程相关函数(例如CreateThread、TerminateThread等)建立多线程应用。html

使用Windows API编写应用没有什么问题,可是当咱们想编写跨平台应用时就显得有点困难。幸运的是phreads目前存在一套Windows平台下的移植版本,称为pthreads-win32。接下来笔者將使用Visual Studio2012做为开发工具,简单的介绍在Win32平台下如何使用这套线程库。ios

pthreads-win32下载

pthreads-win32官方网站:https://sourceware.org/pthreads-win32/编程

在官网上能够找到下载地址,或者点击下面连接下载合适的版本
ftp://sourceware.org/pub/pthreads-win32markdown

笔者使用的是2.9.1版本,解压后能够看到Pre-built.2和pthreads.2文件夹。Pre-built.2为编译好的库文件和头文件,也是咱们将要用到的,pthreads.2目录下为源代码。多线程

pthreads-win32使用

1.使用VS2012建立控制台应用,將字符集设置为多字节字符集。函数

2.將Pre-built.2目录下的include和lib文件夹拷贝到解决方案根目录下。以下图所示:
这里写图片描述
3.在项目上点击右键选择属性,配置属性->VC++目录 下的包含目录添加$(SolutionDir)include库目录添加$(SolutionDir)lib\x86配置属性->连接器->输入->附加依赖项 中添加pthreadVC2.lib工具

4.编写测试代码以下:开发工具

#include "stdafx.h"
#include <pthread.h>
#include <iostream>
//供线程休眠函数pthread_delay_np使用
struct timespec delay = {2 ,0};
void* print_task_1(void* )
{
    while(true)
    {
        std::cout<<"print_task_1 function is called!"<<std::endl;
        pthread_delay_np(&delay);
    }
}
void* print_task_2(void* )
{
    while(true)
    {
        std::cout<<"print_task_2 function is called!"<<std::endl;
        pthread_delay_np(&delay);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    pthread_t handle[2];
    if(pthread_create(&handle[0],0,print_task_1,0))
    {
        std::cout<<"thread create failed!"<<std::endl;
        return EXIT_FAILURE;
    }
    if(pthread_create(&handle[1],0,print_task_2,0))
    {
        std::cout<<"thread create failed!"<<std::endl;
        return EXIT_FAILURE;
    }
    system("pause");
    return 0;
}

在main函数中,咱们经过pthread_create建立两个线程,线程处理函数print_task_1和print_task_2每休息2s后不断向控制台输出语句。调用system(“pause”)使主线程暂停。测试

编译运行能够发现两条线程正常工做,更深刻用法请参考官方提供的文档。网站

这里写图片描述

项目源码:http://download.csdn.net/detail/rongbo_j/8599007

相关文章
相关标签/搜索