This example is suitable for those who are very new to pthread in C in Linux. You will learn on how to use pthread in C program. There is an additional code to be included during compiling the source code.
REQUIREMENT
- Linux Machine
- gcc
- pthread header file
Pthread header file is a standard file. You can just download from the internet from any sources available. (the file name is usually pthread.h)
STEPS
create a new directory, pthreadProgram
mkdir pthreadProgram |
Go into the directory that you have created.
cd pthreadProgram |
Place your downloaded pthread header file (pthread.h) into this directory.
now, create a new c file
vi tprog1.c |
Write down the following codes:
//Program Name: tprog1 //PThread #include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; printf("Hello World! It's me, thread #%ld!\n", tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for(t=0; t<NUM_THREADS; t++){ printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); } } /* Last thing that main() should do */ pthread_exit(NULL); } |
Done with writing the source code.
Press Esc
Then :wq [write and quit vi tool]
In this example, we have fix the number of threads to be 5. You can adjust the
To compile, you can do this in many ways. For this time, we are going to use direct compilation method.
gcc -pthread tprog1.c -o tprog1 |
Note that you need to include “-pthread” option during compiling the program.
If there is no error, you may now execute your program
./tprog1 |
No comments:
Post a Comment