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 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.
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.