Difference between revisions of "Pthread"

From Teknologisk videncenter
Jump to: navigation, search
m (Links)
m
Line 1: Line 1:
 +
=Using pthreads=
 +
==Single thread example==
 +
<source lang=c line>
 +
#include <stdio.h>
 +
#include <pthread.h>
 +
 +
long counter;
 +
void * adder(void * data) {
 +
        for (int i=0; i < 1000000; i++)
 +
                counter++;
 +
}
 +
 +
int main(void) {
 +
        int i;
 +
        pthread_t pt;
 +
 +
        counter=0;
 +
        pthread_create(&pt, NULL, adder, NULL);
 +
        pthread_join(pt, NULL);
 +
        printf("Value of counter is %ld\n", counter);
 +
        return(0);
 +
}
 +
</source>
 
=Releasing resources used by a pthread=
 
=Releasing resources used by a pthread=
 
To release the resources - memory for stack and householding - it is necessary to call either [https://www.man7.org/linux/man-pages/man3/pthread_detach.3.html pthread_detach] or [https://www.man7.org/linux/man-pages/man3/pthread_join.3.html pthread_join]. The resources are not released when the pthread exits without one of these calls.
 
To release the resources - memory for stack and householding - it is necessary to call either [https://www.man7.org/linux/man-pages/man3/pthread_detach.3.html pthread_detach] or [https://www.man7.org/linux/man-pages/man3/pthread_join.3.html pthread_join]. The resources are not released when the pthread exits without one of these calls.

Revision as of 15:27, 17 December 2022

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

Links