Windows下使用pthread-开发环境搭建

描述

本文转自公众号,欢迎关注

Windows下使用pthread-开发环境搭建 (qq.com)

一.Windows下使用pthread-开发环境搭建

嵌入式

1.1 下载源码

1.https://sourceforge.net/projects/pthreads4w/files/ 比官网新一点2018年 3.0版本

2.https://sourceware.org/pthreads-win32/ 官网 最新2012年 2.9.1版本

ftp://sourceware.org/pub/pthreads-win32/ 源码下载

https://sourceware.org/pthreads-win32/manual/index.html API参考

3.https://github.com/GerHobbelt/pthread-win32 适配了MSVC的版本

1.2 库编译

使用上述第3个资源,因为MSVC编译环境都适配好了。

这里使用MSVC2022

打开pthread-win32\\windows\\VS2022\\pthread.2022.sln,

有三个工程分别是,生成动态链接库dll,静态链接库lib和测试的工程。

嵌入式

点击左侧目录,解决方案’pthread.2022’

菜单栏点击 生成->生成解决方案 开始构建

嵌入式

生成的dll和lib位于pthread-win32\\windows\\VS2022\\bin\\Debug-Unicode-64bit-x64下

其中

动态链接库使用

pthread.dll

pthread.dll

静态链接库使用

pthread_static_lib.lib

1.3 测试

在解决方案目录,右键点击属性

嵌入式

修改启动项目

嵌入式

然后点击如下图标运行

嵌入式

pthread-win32\\tests\\wrapper4tests_1.c中测试用例

TEST_WRAPPER(test_sequence2);会失败

先注释掉该用例。

看到测试结果如下:

嵌入式

1.4 在自己工程中使用

1.4.1 使用静态链接库

新建空白WIN32程序

将上述的

pthread.dll

pthread.lib

pthread_static_lib.lib

复制到工程目录Src/pthread/lib下

嵌入式

将源码pthread-win32下的所有.h文件复制到

复制到工程目录Src/pthread/inc下

嵌入式

右键点击工程名->属性

嵌入式

设置Lib文件夹路径

$(MSBuildProjectDirectory)\\Src\\pthread\\lib;

嵌入式

设置lib文件

嵌入式

设置头文件包含路径$(MSBuildProjectDirectory)\\Src\\pthread\\inc;

嵌入式

添加源文件main.c,内容如下

创建两个线程,分别延时不同时间。

#include < stdio.h >
#include < pthread.h >


static void* thread1(void* arg)
{
  const struct timespec interval = { 1L, 500000000L };
  while (1)
  {
    pthread_delay_np(&interval);
    printf("thread1\\r\\n");
  }
  return 0;
}


static void* thread2(void* arg)
{
  const struct timespec interval = { 3L, 0L };
  while (1)
  {
    pthread_delay_np(&interval);
    printf("thread2\\r\\n");
  }
  return 0;
}


int main(void) 
{
  pthread_t t1;
  pthread_t t2;
  pthread_create(&t1, NULL, thread1, NULL);
  pthread_create(&t2, NULL, thread2, NULL);
  while (1);
}

构建项目,然后运行

可以看到基本是thread1运行两次thread运行1次,和其delay时间是两倍关系对应。

嵌入式

使用静态链接库编译的话exe文件可直接运行。

1.4.2 使用动态链接库

与静态链接时一样

只是配置链接的库文件是pthread.lib

嵌入式

运行时需要将exe文件和pthread.dll放在一起。
 

 审核编辑:汤梓红

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分