Working on Pthread

A basic multithreading program in gcc as follows:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void* routine()
{
    printf("This is from threads\n");
}


int main(int argc, char *argv[])
{

    pthread_t t1,t2;
    if(pthread_create(&t1, NULL, &routine,NULL) != 0)
    {
        return 1;
    }
    if(pthread_create(&t2, NULL, &routine,NULL) != 0)
    {
        return 2;
    }
    if(pthread_join(t1, NULL) != 0)
    {
        return 3;
    }
    if(pthread_join(t2, NULL) != 0)
    {
        return 4;
    }

    return 0;
}

Difference between Threads and Process: A single process can have multiple threads and not vice versa. A variables are memory shared between a threads. But in multi process the variables are duplicated.

//Multi Process:
int x = 2;
int pid = fork();
if(pid == 0) //Child Process
{
        x++;
}
printf("value of x: %d\n", x);
printf("Process id %d \n", getpid());

//Output:
value of x: 2
Process id 19502 
value of x: 3
Process id 19503

Above output shows that memory resources are NOT shared between process.

//Multithreading:

int x =20; //Global variable

void*  f1()
{
    x++;
    printf("Value of x %d \n", x);
}

void* f2()
{
    printf("Value of x %d \n", x);
}

main:
 pthread_t t1,t2;
 pthread_create(&t1, NULL, &f1,NULL);
 pthread_create(&t2, NULL, &f2,NULL);
 pthread_join(t1, NULL);
 pthread_join(t2, NULL);

//Output:
Value of x 21 
Value of x 21

Above output shows that memory resources are shared between threads.

Race Condition:

int x = 0;
void* f()
for (size_t i = 0; i < 100000; i++)
{
     x++;
}
main:
 pthread_t t1,t2;
 pthread_create(&t1, NULL, &f,NULL);
 pthread_create(&t2, NULL, &f,NULL);
 pthread_join(t1, NULL);
 pthread_join(t2, NULL);

//Output:
Value of x 137215 //Value is not 200000