The prototype for pthread_create (from the man page) is:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
Things to note:
The first parameter is a pointer to pthread_t.
The start_routine prototype must look like:
void *start(void *)
The final parameter, arg, is a void*.
Bearing these in mind, here are the inline comments to fix your code:
On Fri, March 1, 2013 9:43 pm, Jamie White wrote:
> #include <stdio.h>
> #include <stdlib.h>
> #include <pthread.h>
>
> int main();
> int a_thread(int arg);
Wrong signature. You will need it to look like:
void *a_thread(void *varg);
>
> int main()
> {
> int thread_return, an_arg;
> pthread_t new_thread;
>
> char string[250];
> thread_return = pthread_create(new_thread, NULL, (&a_thread), an_arg);
OK - the 1st, 3rd and 4th args are wrong. Try this instead:
thread_return = pthread_create(&new_thread, // note pointer passed
NULL,
a_thread, // bare fn name decays to fn-ptr
&an_arg // ptr-to-int not bare int
);
> }
>
> int a_thread(*int arg) {
Now we need to fix this to match the prototype mentioned earlier:
void *a_thread(void *varg) {
int arg=*(int *)varg; // cast back to int* and dereference to get value
> printf("test");
Fn returning void * needs a return value. Let's keep it simple:
return 0;
> }
Finally, when you run this, you will find that it still doesn't work. You
should add a pthread_join call to the end of your main function, to wait
for the new thread to finish. Without it, you won't even wait for the
thread to start! Specifically:
pthread_join(new_thread, NULL);
Hope this helps,
Michael