Shwnwil
Shwnwil

Reputation: 67

How to run Pthreads on windows

I used to use a mac to write some C programs but it's 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 didn't work.

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

It keeps saying undefined reference to _imp__pthread_create

How can i fix it?

Upvotes: 4

Views: 14540

Answers (4)

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

//  hello.c
#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:

yes | 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. Bye-bye!

Reference

Upvotes: 1

Demotte
Demotte

Reputation: 713

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.

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612954

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.

Upvotes: 3

Nicholas Smith
Nicholas Smith

Reputation: 11754

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

Upvotes: 3

Related Questions