Created
September 2, 2009 15:50
-
-
Save ankurs/179778 to your computer and use it in GitHub Desktop.
A Simple Pthread example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<pthread.h> | |
#include<stdio.h> | |
// a simple pthread example | |
// compile with -lpthreads | |
// create the function to be executed as a thread | |
void *thread(void *ptr) | |
{ | |
int type = (int) ptr; | |
fprintf(stderr,"Thread - %d\n",type); | |
return ptr; | |
} | |
int main(int argc, char **argv) | |
{ | |
// create the thread objs | |
pthread_t thread1, thread2; | |
int thr = 1; | |
int thr2 = 2; | |
// start the threads | |
pthread_create(&thread1, NULL, *thread, (void *) thr); | |
pthread_create(&thread2, NULL, *thread, (void *) thr2); | |
// wait for threads to finish | |
pthread_join(thread1,NULL); | |
pthread_join(thread2,NULL); | |
return 0; | |
} |
It is better to use -pthread
than -lpthreads
. The -pthread
option can create a define which affect other headers.
It would only matter for more complex examples, but the issues can be mysterious if you extend this example.
Thanks for the easy start.
I had to exchange int with long on my 64bit (Debian based) Raspberry PiOS as you stated.
But it is easier to cast from pointer to pointer that to an int/long.
This little diff produces same behavior and output, and only casts between pointers (to and from void*):
pi@raspberrypi5:~/RR/tsp/pthread $ diff thread.c.orig thread.c
9,10c9,10
< int type = (int) ptr;
< fprintf(stderr,"Thread - %d\n",type);
---
> int *type = (int*) ptr;
> fprintf(stderr,"Thread - %d\n",*type);
21,22c21,22
< pthread_create(&thread1, NULL, *thread, (void *) thr);
< pthread_create(&thread2, NULL, *thread, (void *) thr2);
---
> pthread_create(&thread1, NULL, *thread, (void *) &thr);
> pthread_create(&thread2, NULL, *thread, (void *) &thr2);
pi@raspberrypi5:~/RR/tsp/pthread $
I did not have to specify -pthread or -lpthread, seems to be dobe by default:
pi@raspberrypi5:~/RR/tsp/pthread $ gcc -Wall -pedantic thread.c
pi@raspberrypi5:~/RR/tsp/pthread $ ./a.out
Thread - 1
Thread - 2
pi@raspberrypi5:~/RR/tsp/pthread $
Adding "-Wextra" reveals that argc and argv are unused parameters.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dunno how I got here, but just a note; 64bit systems will want you to cast to a
long
on line 9. On 32 bit systems, this should compile fine, theoretically.