MinGW下pthread和openMP的配置

本文介绍在MinGW环境下配置pthread和openMP的过程及遇到的问题。包括安装缺失的pthread库,解决编译错误,调整编译参数等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MinGW下pthread和openMP的配置

http://blog.youkuaiyun.com/abacn/article/details/45153579

标签: C++并行编程

  900人阅读  评论(0)  收藏  举报
  分类:

开始看openMP这个库,学习多线程编程。

下载并安装minGW,编译openMP的测试程序:gcc -std=c99 -fopenmp omptest.c -o omptest.exe

编译失败,提示cannot find -lpthread

搜索发现MinGW的pthread不是默认安装的,打开包管理器,发现确实没有安装pthread库:


把"mingw32-pthreads-w32"勾上,菜单栏->Installation->Apply Changes即可。

编译能通过了。

但是编译包含了<pthreads.h>的文件,例如这个时间复杂度等于o(max(elements))的线程排序:

[cpp]  view plain  copy
  1. #include <pthread.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #define NUM_THREADS 9  
  5.     
  6. void * SortThreadFunc(void *threadid)  
  7. {  
  8.    int ms;  
  9.    ms = (int)threadid;  
  10.    _sleep(ms*10+10);  
  11.    printf("%d", ms);  
  12.    pthread_exit(NULL);  
  13. }  
  14.     
  15. int main (int argc, char *argv[])  
  16. {  
  17.    pthread_t threads[NUM_THREADS];  
  18.    int ints[] = {1,4,7,3,8,9,2,6,5};  
  19.    int rc;  
  20.    long t;  
  21.    for(t=0; t<NUM_THREADS; t++){  
  22.       rc = pthread_create(&threads[t], NULL, SortThreadFunc, (void *)ints[t]);  
  23.       if (rc){  
  24.          printf("ERROR; return code from pthread_create() is %d\n", rc);  
  25.          exit(-1);  
  26.       }  
  27.    }  
  28.    pthread_exit(NULL);  
  29. }  

F:\cpp\小程序>gcc thread_sort.c -o thread_sort又编译失败:

[plain]  view plain  copy
  1. thread_sort.c: In function 'SortThreadFunc':  
  2. thread_sort.c:10:4: warning: '_sleep' is deprecated (declared at c:\mingw\includ  
  3. e\stdlib.h:280) [-Wdeprecated-declarations]  
  4.     _sleep(ms*10+10);  
  5.     ^  
  6. C:\Users\Aba\AppData\Local\Temp\ccws7X69.o:thread_sort.c:(.text+0x3e): undefined  
  7.  reference to `_imp__pthread_exit'  
  8. C:\Users\Aba\AppData\Local\Temp\ccws7X69.o:thread_sort.c:(.text+0xdf): undefined  
  9.  reference to `_imp__pthread_create'  
  10. C:\Users\Aba\AppData\Local\Temp\ccws7X69.o:thread_sort.c:(.text+0x133): undefine  
  11. d reference to `_imp__pthread_exit'  
  12. c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\A  
  13. ba\AppData\Local\Temp\ccws7X69.o: bad reloc address 0x20 in section `.eh_frame'  
  14. c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link  
  15.  failed: Invalid operation  
  16. collect2.exe: error: ld returned 1 exit status  

百度未果。后搜索英文网页找到解决方法:“Move -lpthread to the end of that command:The order of the arguments is important.”把编译参数-lpthread移至末尾即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值