How to run pthreads on windows

余生长醉 提交于 2020-12-23 02:44:59

问题


I used to use a mac to write some c programs but its not working now.. I have to use an old windows laptop for a while..

I installed codeblocks and tested a simple program using pthreads. Unfortunately it didnt work..

  pthread_create(&thrd1, NULL, thread_execute, (void *)t);

It keeps saying undefined reference to 'imp_pthread_create'

how can i fix it and will i face similar problems writing these sort of programs?

Thanks


回答1:


You've clearly got a version of pthreads for Windows. You just haven't included the .lib file in your linker settings. Do that and you should be golden.




回答2:


You need to grab pthreads-win32 as pthreads is a Unix component not a Windows one.




回答3:


If you are using MinGW you can MinGW installation manager and install packages that need to execute pthreads and openmp related tasks. Here is the procedure.

After opening the installation manager go to all packages and select the select packages named using mingw32-pthreads-w32 and select them for installation.

Then go to the installation -> Apply changes to install new packages. The you can use pthread.h and omp.h inside your c or c++ program without any problem.




回答4:


This code works fine in an MSYS2 terminal on Windows.
All you need to do to make it run is to install gcc. (See further below.)

//  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;
}

Compile and run as follows:

gcc -fopenmp -pthread hello.c && ./a.out # Linux
gcc -fopenmp -pthread hello.c && ./a.exe # MSYS2, Windows

As you can see, the only difference between Linux and MSYS2 on Windows is the name of the executable binary. Everything else is identical. I tend to think of MSYS2 as an emulated (Arch-)Linux terminal on Windows.

To install gcc in MSYS2:

pacman -Syu gcc

Expect output similar to:

 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!

Reference: https://www.msys2.org/wiki/MSYS2-installation/



来源:https://stackoverflow.com/questions/7542286/how-to-run-pthreads-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!