开发者

Bus error on OSX - pthreads

开发者 https://www.devze.com 2023-01-08 14:11 出处:网络
am trying to get my head around the fo开发者_JAVA技巧llowing: Have a small program am trying to port to OSX(intel) which calls function doWork()

am trying to get my head around the fo开发者_JAVA技巧llowing:

Have a small program am trying to port to OSX(intel) which calls function doWork() via pthread_create, in the function, I start by creating an array of long like such:

long myarray[DIMENSION]

on OSX, for the following values of DIMENSION, I get the following:

0->65434 = fine
65435->67037 = SIGBUS
67037+ = SIGSEGV

I'm totally confused here, I understand that SIGBUS is due to memory alignment issues usually, I checked sizeof(long) and it appears to be 8 on this platform. Can somebody point me in the right direction of docs I should be reading here?

Here is the source:


#include pthread.h
#include stdio.h
#define NUM_THREADS     5
#define DIMENSION       12345

void *doStuff(void *threadid)
{
   long array[DIMENSION];
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t lt NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, doStuff, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}


It would appear you're overflowing the stack.

You'll need to either turn the long array into a malloced one, or use pthread_attr_setstacksize and friends to create a larger stack when you call pthread_create.

Default thread stack sizes vary a lot between platforms, which would explain why the code works on other platforms.

Example code:

   pthread_attr_t attr;
   size_t stacksize;

   pthread_attr_init(&attr);
   pthread_attr_getstacksize(&attr, &stacksize);
   printf("Default stack size = %li\n", stacksize);
   stacksize = <....>;
   printf("Amount of stack needed per thread = %li\n",stacksize);
   pthread_attr_setstacksize(&attr, stacksize);
   rc = pthread_create(&thread, &attr, dowork, (void *)t);

(code originally from https://github.com/LLNL/HPC-Tutorials/blob/main/posix/stack_management.md )

As to why you get a sigbus, it's probably because the act of creating the array is overwriting some part of pthreads internal data structures with garbage, resulting in an alignment error when pthreads tries to clean up the thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消