Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simple pthread prog: segmentation fault

Trying to see how pthread works by running a simple program but I am getting segmentation fault (core dumped) at pthread_create

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void* testfunc(void* arg) {
  while (1) {
    printf("testfunc");
  }
}

int main(void) {
  printf("helo\n");

  if (pthread_create(NULL, NULL, &testfunc, NULL) != 0) {
    perror("pthread failed to create\n");
  }

  while (1) {
    printf("main function\n");
    sleep(1000);
  } 

  return 0;
}

What seems to be causing the problem? I am on Ubuntu 20.04 if that matters.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t pass NULL for pthread_create‘s first argument.

Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread

Also, pthread_create doesn’t set errno, so using perror makes no sense, at least not without some prep.

on error, it returns an error number, and the contents of *thread are undefined.

Fixed:

pthread_t thread;
if ( ( errno = pthread_create(&thread, NULL, &testfunc, NULL) ) != 0 ) {
    perror("pthread failed to create\n");
}

...

pthread_join(thread);  // Normally.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading