0% found this document useful (0 votes)
67 views11 pages

Jss Academy of Technical Education: Multithreading

The document discusses multithreading programming using different APIs. It provides code samples for implementing multithreading using the Windows API, Java threads using the Runnable interface, and Pthreads API in C language. The Windows API sample creates multiple threads to bounce different colored characters on the screen. The Java code shows creating multiple threads by implementing Runnable and starting each thread. The Pthreads code sample creates two threads, one by pthread_create and another in main, each printing a counter for delay.

Uploaded by

Trishala Kumari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views11 pages

Jss Academy of Technical Education: Multithreading

The document discusses multithreading programming using different APIs. It provides code samples for implementing multithreading using the Windows API, Java threads using the Runnable interface, and Pthreads API in C language. The Windows API sample creates multiple threads to bounce different colored characters on the screen. The Java code shows creating multiple threads by implementing Runnable and starting each thread. The Pthreads code sample creates two threads, one by pthread_create and another in main, each printing a counter for delay.

Uploaded by

Trishala Kumari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

JSS MAHAVIDYAPEETHA, MYSURU

JSS ACADEMY OF TECHNICAL EDUCATION


JSS Campus, Dr.Vishnuvardhan Road, Bengaluru-560060

DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

ASSIGNMENT-3
of

OPERATING SYSTEM[17CS64]

TOPIC NAME:

MULTITHREADING

Submitted by:
NAME: TRISHALA KUMARI USN: 1JS17IS082
SEMESTER:6th SEC: B

Under the Guidance of


Dr. Chayadevi M.L
Asso. Professor, Dept. of ISE, JSSATE
1.Multithread programming using the Windows API
// sample_multithread_c_program.c
// compile with: /c
//
// Bounce - Creates a new thread each time the letter 'a' is typed.
// Each thread bounces a character of a different color around
// the screen. All threads are terminated when the letter 'Q' is
// entered.
//

#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>

#define MAX_THREADS 32

// The function getrandom returns a random number between


// min and max, which must be in integer range.
#define getrandom( min, max ) (SHORT)((rand() % (int)(((max) + 1) - \
(min))) + (min))

int main(void); // Thread 1: main


void KbdFunc(void); // Keyboard input, thread dispatch
void BounceProc(void* MyID); // Threads 2 to n: display
void ClearScreen(void); // Screen clear
void ShutDown(void); // Program shutdown
void WriteTitle(int ThreadNum); // Display title bar information

HANDLE hConsoleOut; // Handle to the console


HANDLE hRunMutex; // "Keep Running" mutex
HANDLE hScreenMutex; // "Screen update" mutex
int ThreadNr; // Number of threads started
CONSOLE_SCREEN_BUFFER_INFO csbiInfo; // Console information
COORD consoleSize;
BOOL bTrails;
int main() // Thread One
{
// Get display screen information & clear the screen.
hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsoleOut, &csbiInfo);
consoleSize.X = csbiInfo.srWindow.Right;
consoleSize.Y = csbiInfo.srWindow.Bottom;
ClearScreen();
WriteTitle(0);

// Create the mutexes and reset thread count.


hScreenMutex = CreateMutexW(NULL, FALSE, NULL); // Cleared
hRunMutex = CreateMutexW(NULL, TRUE, NULL); // Set
ThreadNr = 0;
bTrails = FALSE;

// Start waiting for keyboard input to dispatch threads or exit.


KbdFunc();

// All threads done. Clean up handles.


if (hScreenMutex) CloseHandle(hScreenMutex);
if (hRunMutex) CloseHandle(hRunMutex);
if (hConsoleOut) CloseHandle(hConsoleOut);
}

void ShutDown(void) // Shut down threads


{
while (ThreadNr > 0)
{
// Tell thread to die and record its death.
ReleaseMutex(hRunMutex);
ThreadNr--;
}

// Clean up display when done


WaitForSingleObject(hScreenMutex, INFINITE);
ClearScreen();
}

void KbdFunc(void) // Dispatch and count threads.


{
int KeyInfo;

do
{
KeyInfo = _getch();
if (tolower(KeyInfo) == 'a' &&
ThreadNr < MAX_THREADS)
{
ThreadNr++;
_beginthread(BounceProc, 0, &ThreadNr);
WriteTitle(ThreadNr);
}
if (tolower(KeyInfo) == 't')
{
bTrails = !bTrails;
}
} while (tolower(KeyInfo) != 'q');

ShutDown();
}

void BounceProc(void* pMyID)


{
wchar_t MyCell, OldCell;
WORD MyAttrib, OldAttrib = 0;
wchar_t BlankCell = 0x20;
COORD Coords, Delta;
COORD Old = { 0,0 };
DWORD Dummy;
char* MyID = (char*)pMyID;

// Generate update increments and initial


// display coordinates.
srand((unsigned int)* MyID * 3);

Coords.X = getrandom(0, consoleSize.X - 1);


Coords.Y = getrandom(0, consoleSize.Y - 1);
Delta.X = getrandom(-3, 3);
Delta.Y = getrandom(-3, 3);
// Set up character & generate color
// attribute from thread number.
if (*MyID > 16)
MyCell = 0x60 + *MyID - 16; // lower case
else
MyCell = 0x40 + *MyID; // upper case
MyAttrib = *MyID & 0x0f; // force black background

do
{
// Wait for display to be available, then lock it.
WaitForSingleObject(hScreenMutex, INFINITE);

if (!bTrails)
{
// If we still occupy the old screen position, blank it out.
ReadConsoleOutputCharacterW(hConsoleOut, &OldCell, 1,
Old, &Dummy);
ReadConsoleOutputAttribute(hConsoleOut, &OldAttrib, 1,
Old, &Dummy);
if ((OldCell == MyCell) && (OldAttrib == MyAttrib))
WriteConsoleOutputCharacterW(hConsoleOut, &BlankCell, 1,
Old, &Dummy);
}

// Draw new character, then clear screen lock


WriteConsoleOutputCharacterW(hConsoleOut, &MyCell, 1,
Coords, &Dummy);
WriteConsoleOutputAttribute(hConsoleOut, &MyAttrib, 1,
Coords, &Dummy);
ReleaseMutex(hScreenMutex);

// Increment the coordinates for next placement of the block.


Old.X = Coords.X;
Old.Y = Coords.Y;
Coords.X += Delta.X;
Coords.Y += Delta.Y;

// If we are about to go off the screen, reverse direction


if (Coords.X < 0 || Coords.X >= consoleSize.X)
{
Delta.X = -Delta.X;
Beep(400, 50);
}
if (Coords.Y < 0 || Coords.Y > consoleSize.Y)
{
Delta.Y = -Delta.Y;
Beep(600, 50);
}
}
// Repeat while RunMutex is still taken.
while (WaitForSingleObject(hRunMutex, 75L) == WAIT_TIMEOUT);
}

void WriteTitle(int ThreadNum)


{
enum
{
sizeOfNThreadMsg = 120
};
wchar_t NThreadMsg[sizeOfNThreadMsg] = { L"" };

swprintf_s(NThreadMsg, sizeOfNThreadMsg,
L"Threads running: %02d. Press 'A' "
L"to start a thread, 'T' to toggle "
L"trails, 'Q' to quit.", ThreadNum);
SetConsoleTitleW(NThreadMsg);
}

void ClearScreen(void)
{
DWORD dummy = 0;
COORD Home = { 0, 0 };
FillConsoleOutputCharacterW(hConsoleOut, L' ',
consoleSize.X * consoleSize.Y,
Home, &dummy);
}
Output:
2.JAVA thread implementation

// Java code for thread creation by implementing


// the Runnable Interface
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<n; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output:

3. Multithread programming using the Pthreads API


#include <stdio.h> /* standard I/O routines */
#include <pthread.h> /* pthread functions and data structures */

/* function to be executed by the new thread */


void*
do_loop(void* data)
{

int i; /* counter, to print numbers */


int j; /* counter, for delay */
int me = *((int*)data); /* thread identifying number */

for (i=0; i<10; i++) {


for (j=0; j<500000; j++) /* delay loop */
;
printf("'%d' - Got '%d'\n", me, i);
}

/* terminate the thread */


pthread_exit(NULL);
}

/* like any C program, program's execution begins in main */


int
main(int argc, char* argv[])
{
int thr_id; /* thread ID for the newly created thread */
pthread_t p_thread; /* thread's structure */
int a = 1; /* thread 1 identifying number */
int b = 2; /* thread 2 identifying number */

/* create a new thread that will execute 'do_loop()' */


thr_id = pthread_create(&p_thread, NULL, do_loop, (void*)&a);
/* run 'do_loop()' in the main thread as well */
do_loop((void*)&b);

/* NOT REACHED */
return 0;
}
Output:

You might also like