Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bus error on OSX - pthreads

Tags:

c

macos

pthreads

am trying to get my head around the following:

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

like image 520
lochii Avatar asked Oct 16 '25 14:10

lochii


1 Answers

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.

like image 67
JosephH Avatar answered Oct 18 '25 07:10

JosephH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!