[英]How to run pthreads on windows
我以前用 mac 寫一些 c 程序,但現在不能工作了..我不得不使用舊的 Windows 筆記本電腦一段時間..
我安裝了代碼塊並使用 pthreads 測試了一個簡單的程序。 不幸的是它沒有工作..
pthread_create(&thrd1, NULL, thread_execute, (void *)t);
它一直說對' imp _pthread_create'的未定義引用
我該如何修復它,我會在編寫此類程序時遇到類似的問題嗎?
謝謝
如果您使用的是 MinGW,您可以使用 MinGW 安裝管理器並安裝需要執行 pthreads 和 openmp 相關任務的包。 這是程序。
打開安裝管理器后,轉到所有包並選擇使用 mingw32-pthreads-w32 命名的包並選擇它們進行安裝。
然后轉到安裝 -> 應用更改以安裝新軟件包。 您可以在 c 或 c++ 程序中使用 pthread.h 和 omp.h 沒有任何問題。
您需要獲取pthreads-win32,因為 pthreads 是 Unix 組件而不是 Windows 組件。
您顯然已經獲得了適用於 Windows 的 pthreads 版本。 您只是沒有在鏈接器設置中包含 .lib 文件。 這樣做,你應該是金色的。
此代碼在 Windows 上的 MSYS2 終端中運行良好。
讓它運行所需要做的就是安裝gcc
。 (見下文。)
// hello.c
// https://stackoverflow.com/questions/33876991
#include <omp.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *print_hello(void *thrd_nr) {
printf("Hello World. - It's me, thread #%ld\n", (long)thrd_nr);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
printf(" Hello C code!\n");
const int NR_THRDS = omp_get_max_threads();
pthread_t threads[NR_THRDS];
for(int t=0;t<NR_THRDS;t++) {
printf("In main: creating thread %d\n", t);
pthread_create(&threads[t], NULL, print_hello, (void *)(long)t);
}
for(int t=0;t<NR_THRDS;t++) {
pthread_join(threads[t], NULL);
}
printf("After join: I am always last. Byebye!\n");
return EXIT_SUCCESS;
}
編譯運行如下:
gcc -fopenmp -pthread hello.c && ./a.out # Linux
gcc -fopenmp -pthread hello.c && ./a.exe # MSYS2, Windows
如您所見,Linux 和 Windows 上的 MSYS2 之間的唯一區別是可執行二進制文件的名稱。 其他一切都是相同的。 我傾向於將 MSYS2 視為 Windows 上的模擬 (Arch-)Linux 終端。
在 MSYS2 中安裝gcc
:
pacman -Syu gcc
期望輸出類似於:
Hello C code!
In main: creating thread 0
Hello World. - It's me, thread #0
In main: creating thread 1
Hello World. - It's me, thread #1
After join: I am always last. Byebye!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.