Sunday, April 19, 2020

Threads in C - Input and Output

Today, we will see only to pass values to a thread.  Retrieve value from thread.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

//Thread to change value from 20 to 30
void * threadtak (void * poin)
{
    int *inttak = (int *)poin;
    *inttak=30;
    return NULL;
}

//Thread to return a value 60
void * threadret ()
{
  int *ret=malloc(sizeof(int));
  *ret=60;
  printf("%d\n",*ret);
  return ret;
}
int main()
{
    pthread_t tak,ret;
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    int vartak=20;
    pthread_create(&tak, &attr,threadtak, &vartak);
    pthread_join(tak,NULL);
    printf("Modified vartak = %d\n",vartak);

    int *varret;
    pthread_create(&ret, &attr,threadret, NULL);
    pthread_join(ret,(void *)&varret);
    printf("Returned varret=%d\n",*varret);
    
    return 0;
}

Lets break the explanation into 2.

Passing the value

Line 29: Address of vartak is passed as argument
Line 9: As it is declared void pointer, it can take the address of integer/any other data type.
Line 10: Value at inttak is changed to 30
Line 11: Returned as NULL
Line 31: vartak is already changed and can be accessed as normal int


1
2
3
4
5
# gcc -pthread -o a.out main.c
# ./a.out
Modified vartak = 30
60
Returned varret=60

Value is vartak is displayed as 30

Returning the value

Line 33: We try to retrieve the value from threadret into integer pointer.
Line 34: As we are not passing any argument to the thread, we keep it NULL
Line 15: The argument for the thread can be kept blank as no argument is passed
Line 17: We create a memory and assign the value 60
Line 20: Return the address of ret
Line 35: Join should have void **.  We keep it &varret.  Because, *varret is value. varret is the address of *varret. &varret is the address of varret.


1
2
3
4
5
# gcc -pthread -o a.out main.c
# ./a.out
Modified vartak = 30
60
Returned varret=60

Value of varret is displayed as 60.

No comments:

Post a Comment