开始看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))的线程排序:
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM_THREADS 9
-
- void * SortThreadFunc(void *threadid)
- {
- int ms;
- ms = (int)threadid;
- _sleep(ms*10+10);
- printf("%d", ms);
- pthread_exit(NULL);
- }
-
- int main (int argc, char *argv[])
- {
- pthread_t threads[NUM_THREADS];
- int ints[] = {1,4,7,3,8,9,2,6,5};
- int rc;
- long t;
- for(t=0; t<NUM_THREADS; t++){
- rc = pthread_create(&threads[t], NULL, SortThreadFunc, (void *)ints[t]);
- if (rc){
- printf("ERROR; return code from pthread_create() is %d\n", rc);
- exit(-1);
- }
- }
- pthread_exit(NULL);
- }
F:\cpp\小程序>gcc thread_sort.c -o thread_sort又编译失败:
- thread_sort.c: In function 'SortThreadFunc':
- thread_sort.c:10:4: warning: '_sleep' is deprecated (declared at c:\mingw\includ
- e\stdlib.h:280) [-Wdeprecated-declarations]
- _sleep(ms*10+10);
- ^
- C:\Users\Aba\AppData\Local\Temp\ccws7X69.o:thread_sort.c:(.text+0x3e): undefined
- reference to `_imp__pthread_exit'
- C:\Users\Aba\AppData\Local\Temp\ccws7X69.o:thread_sort.c:(.text+0xdf): undefined
- reference to `_imp__pthread_create'
- C:\Users\Aba\AppData\Local\Temp\ccws7X69.o:thread_sort.c:(.text+0x133): undefine
- d reference to `_imp__pthread_exit'
- c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\A
- ba\AppData\Local\Temp\ccws7X69.o: bad reloc address 0x20 in section `.eh_frame'
- c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link
- failed: Invalid operation
- collect2.exe: error: ld returned 1 exit status
百度未果。后搜索英文网页找到解决方法:“Move -lpthread to the end of that command:The order of the arguments is important.”把编译参数-lpthread移至末尾即可。