Reading and writing in the array using threads
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). Arrays are used to store homogeneous data. The conventional way of storing the elements in an array and reading the elements from an array takes a lot of time if there are numerous elements.
Writing and reading elements in an array is a small problem where each element is first added to the array and then the entire array is read element by element and printed on the console. But when the number of elements is too large, it could take a lot of time. But this could be solved by dividing the writing and reading tasks into parts.
This could be done by using multi-threading where each core of the processor is used. In this case, two threads are used, where one thread is responsible for writing to the array and the other thread is responsible for reading the array. In this way, the performance of a program can be improved as well as the cores of the processor can be utilized. It is better to use one thread for each core. Although one can create as many threads as required for a better understanding of multi-threading.
This article focuses on writing and reading the elements of the array using the concept of multithreading.
Approach: This section states the algorithm that is followed to design a program to writing and read elements of an array using multithreading:
- In the first step, two threads will be created.
- One for writing operation and one for reading operation.
- Here the synchronized keyword is used with the array so that only one thread can access the array at a time.
- First, the write operation will be performed on the array.
- Then, the read operation is performed on the array.
Below is the Java program to implement the above approach-
C++14
#include <iostream>
#include <thread>
using namespace std;
int main()
{
int a[5];
thread t1([]() {
lock_guard<mutex> lock(m);
cout << "Enter the elements : " << endl;
for ( int i = 0; i < 5; i++) {
cin >> a[i];
}
cout << "Writing done Successfully" << endl;
});
thread t2([]() {
lock_guard<mutex> lock(m);
cout << "The elements are : " << endl;
for ( int i = 0; i < 5; i++) {
cout << a[i] << endl;
}
cout << "Reading done successfully" << endl;
});
t1.join();
t2.join();
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
int a[] = new int [ 5 ];
Thread t1 = new Thread( new Runnable() {
public void run()
{
synchronized (a)
{
Scanner s = new Scanner(System.in);
System.out.println(
"Enter the elements : " );
for ( int i = 0 ; i < 5 ; i++) {
a[i] = s.nextInt();
}
System.out.println(
"Writing done Successfully" );
}
}
});
Thread t2 = new Thread( new Runnable() {
public void run()
{
synchronized (a)
{
System.out.println(
"The elements are : " );
for ( int i = 0 ; i < 5 ; i++) {
System.out.println(a[i]);
}
System.out.println(
"Reading done successfully" );
}
}
});
t1.start();
t2.start();
}
}
|
Python3
import threading
a = [ 0 ] * 5
lock = threading.Lock()
t1 = threading.Thread(target = lambda : write_thread())
t2 = threading.Thread(target = lambda : read_thread())
def write_thread():
global a
global lock
with lock:
print ( "Enter the elements:" )
for i in range ( 5 ):
a[i] = int ( input ())
print ( "Writing done successfully" )
def read_thread():
global a
global lock
with lock:
print ( "The elements are:" )
for i in range ( 5 ):
print (a[i])
print ( "Reading done successfully" )
t1.start()
t2.start()
t1.join()
t2.join()
|
C#
using System;
using System.Threading;
public class GFG
{
static public void Main()
{
int [] a = new int [5];
Thread t1 = new Thread(() => {
lock (a) {
Console.WriteLine( "Enter the elements : " );
for ( int i = 0; i < 5; i++) {
a[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine( "Writing done Successfully" );
}
});
Thread t2 = new Thread(() => {
lock (a) {
Console.WriteLine( "The elements are : " );
for ( int i = 0; i < 5; i++) {
Console.WriteLine(a[i]);
}
Console.WriteLine( "Reading done successfully" );
}
});
t1.Start();
t2.Start();
}
}
|
Javascript
let a = new Array(5);
let t1 = new Thread(() => {
lock_guard.lock(m);
console.log( "Enter the elements : " );
for (let i = 0; i < 5; i++) {
a[i] = prompt();
}
console.log( "Writing done Successfully" );
});
let t2 = new Thread(() => {
lock_guard.lock(m);
console.log( "The elements are : " );
for (let i = 0; i < 5; i++) {
console.log(a[i]);
}
console.log( "Reading done successfully" );
});
t1.start();
t2.start();
|
Output:
Explanation: Here, firstly the write thread is started and at that time read thread will not interfere as the array is synchronized. Similarly, during reading, write thread will not interfere.
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...