Pthread
From Teknologisk videncenter
Using pthreads
Single thread example
1 #include <stdio.h>
2 #include <pthread.h>
3
4 long counter;
5 void * adder(void * data) {
6 for (int i=0; i < 1000000; i++)
7 counter++;
8 }
9
10 int main(void) {
11 int i;
12 pthread_t pt;
13
14 counter=0;
15 pthread_create(&pt, NULL, adder, NULL);
16 pthread_join(pt, NULL);
17 printf("Value of counter is %ld\n", counter);
18 return(0);
19 }
Releasing resources used by a pthread
To release the resources - memory for stack and householding - it is necessary to call either pthread_detach or pthread_join. The resources are not released when the pthread exits without one of these calls.
- pthread_join is called by the process or another thread.
- pthread_detach is typically called by the thread itself to release the resources when the thread terminates