• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

[Programming-Age] Anybody out there know Unix code?

Status
Not open for further replies.

Shawn128

Member
I need a bit of help with a programming assignment and I was hoping someone here could point out what I'm doing wrong. Essentially, I'm trying to create a pthread inside my program. I've looked up literature in my books and also through google, yet I still return an error when I try to use pthread_create(). Here's basically what my code looks like (Oh this is in C btw if I haven't mentioned so already):


Code:
#include <pthread.h>
#include <stdio.h>

void *runner (void *param)
{
    printf("Inside pthread\n");
}

int main(int argc, char * argv[])
{
  int rc;
  pthread_t tid;
  pthread_attr_t attr;
  
  pthread_attr_init(&attr);
  printf("before\n");
  rc = pthread_create(&tid,NULL,runner,(void *)5);
  printf("after\n");
  
  if (rc){
    printf("ERROR; return code from pthread_create() is %d\n", rc);
    exit(-1);
  }

  pthread_join(tid,NULL); 
}
 
You're casting a literal (the numeral 5) to a void pointer? I'm not sure you can do that.

Try storing the 5 in a variable and casting that instead.
 

Shawn128

Member
Its not really the fact that I'm casting a numeral. The problem is getting into the pthread period. Even if I can't do that, I should be able to at least get the printf() in the runner function to print onscreen
 

Shawn128

Member
This is what I get for my output:

Code:
>>a.out

before
after
ERROR; return code from pthread_create() is -1

>>
 
It's been a while since I had to do Unix programming, but it seems like you had to pass a reference to a variable as your last parameter to p_thread_creat, just like you passed the reference to tid.
 

Shawn128

Member
i think i just figured it out.

apparently you can't just compile it as gcc simple.c

you have to do it as: gcc simple.c -lpthread

Thanks for the help guys, but I'd like to keep the thread going. Anyone have any advice on pthreads in general?
 
Yeah, just for consistency to what you had, if you declare an integer equal to 5, and pass a reference to it, it will compile. Also, unless you want inconsistent results where you might get the output:
before
after
inside pthread

or:
before
inside pthread
after

you might want to call the p_threadjoin immediately after creating the thread. That function is what tells main to wait for the thread to complete.
 
Status
Not open for further replies.
Top Bottom