Pthread
Pthread
by Tanmoy Maitra
Functions on pthread:
<pthread.h>
• Thread Creation:
int pthread_create(pthread_t *restrict thread, const pthread_attr_t
*restrict attr, typeof(void *(void *)) *start_routine, void *restrict arg);
On success, pthread_create() returns 0; on error, it returns an error
number
• Thread Join:
int pthread_join(pthread_t thread, void **value_ptr);
If successful, the pthread_join() function returns 0; otherwise, an error
number
Example 1: Single Thread Creation without Passing any
Argument
void *example(); Attributes of x1
Store ID of x1
int main() { Passing Arg. by x1
pthread_t x1;
pthread_create(&x1, NULL, example, NULL);
pthread_join(x1, NULL); Return value by example procedure
return 0; }
void *example() { Run
$> gcc -o p1 a.c
printf(“Example of single thread”); $> ./p1
Example of single thread
return NULL; }
Example 2: Single Thread Creation with Passing Argument
................
pthread_join(x1, (void**) &res1); pthread_join(x2, (void**) &res2);
printf(“Result 1 = %d\n”, *res1); printf(“Result 2 = %d\n”, *res2);
free (res1); free(res2);
return 0; }
void *example(void *y1) { int add = 0;
int* result = malloc(sizeof(int));
int *y2 = (int *) (y1); Run
for (int i=0; i<100; i++) add = add + *y2; $> gcc -o p7 h.c
*result = add; $> ./p7
return (void*) result; } ......