Thread 1

Lab06_Problem01: Write a C program that will create two threads. One thread stores values into global array and other thread print the values from the global array. Now synchronized the problem solution by using mutex lock.



#include 
#include 
#include 
#include 
#include 
  
pthread_t tid[2];
int a[10];
int count1 = 0,count2 = 0;

void* store(void* arg)
{
    a[count1] = 1;
    count1 ++;
    return NULL;
}

void* print(void* arg)
{
    printf("%d ",a[count2]);
    count2 ++;
}

int main()
{
    int error;
    for(int i=1;i<=20;i++)
    {
        if(i%2)
            error = pthread_create(&(tid[0]), NULL, &store, NULL);
        else
            error = pthread_create(&(tid[1]), NULL, &print, NULL);
        if (error != 0)
            printf("\nThread can't be created : [%s]", strerror(error));
    }
    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    return 0;
}


Explanation : assigning the value '1' to the elements of the array . using a thread , and using another to print the values , synchronising the problem by applying mutex lock .

The code is written on ubuntu , it will run fine on all linux distro .

use this to compile .

$ gcc -o filename filename.c -lpthread

$ ./filename

1 1 1 1 1 1 1 1 1 1

Previous Post Next Post