Sunday, April 12, 2020

Threads in C

We have seen how fork() works in C.  They say, threads are light-weight processes.  Will see how it is done.  Sample program with 3 threads is given here:

 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
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void * threadrun (void * poin)
{
    int k=*(int *)poin;
    
    for (int i=1;i<5;i++)
    {
      sleep(2);
      printf("iteration %d of thread %d\n",i,k);
    }
    return NULL;
}

int main()
{
    pthread_t tid1,tid2,tid3;
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    int p=1;
    pthread_create(&tid1, &attr,threadrun, &p);
    int q=2;
    pthread_create(&tid2, &attr,threadrun, &q);
    int r=3;
    pthread_create(&tid3, &attr,threadrun, &r);
    
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    
    return 0;
}

The thread function should take in a void pointer, return a void pointer to a pointer.  The function threadrun will print 4 iterations each while sleeping 2 seconds for each iteration.  We are returning NULL.

Thread Creation
Line 19 - Create an identifier
Line 20/21 - Create an attribute structure and initialize
Line 23 - Create a value to pass it to thread, so that we can identify the thread
Line 24 - Start the Thread

After thread is created, they will start executing independent of each other.  You can see the stdout the sequence in which the prints are made.

Thread Join
Line 30 - We wait till thread1 is returned.
Line 31 - We wait till thread2 is returned
Line 32 - We wait till thread3 is returned

As Thread1 is first in line,  even though thread 2 and 3 returns earlier, our program will wait till thread1 is completed.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# ./thread
iteration 1 of thread 1
iteration 1 of thread 3
iteration 1 of thread 2
iteration 2 of thread 1
iteration 2 of thread 2
iteration 2 of thread 3
iteration 3 of thread 3
iteration 3 of thread 2
iteration 3 of thread 1
iteration 4 of thread 3
iteration 4 of thread 2
iteration 4 of thread 1

No comments:

Post a Comment