Friday, October 14, 2011

Simple Multithreading Application sample source code in pure C

In our general program we can’t run two process at same time for e.g we can’t run two for loop at same time.For running two process at same time we need Multithreading.In C we do it by the _beginthread and
_endthread run time  library function.All the above c run time library functions are in the process.h header file.

Header
process.h

Prototype

unsigned long _beginthread(void(* func)(void*), unsigned stack_size, void *arg);

Description




This function creates a new thread of execution within the current process. Thread execution starts at the beginning of func. To terminate the thread correctly, func must call _endthread, freeing memory allocated by the run time library to support the thread.
The operating system allocates a stack for the thread containing the number of bytes specified by stack_size. If stack_size is zero, the operating system creates a stack the same size as that of the main thread.
The operating system passes arg to func when execution begins. arg can be any 32-bit value cast to void *.

Return Value

Returns the operating system handle of the newly created thread. If unsuccessful, the function returns -1 and sets error.
Here is the sample source code, copy and compile it in codeblocks.
#include <process.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
#include <windows.h>
int j;
int i;
 
static void error(char *action)
{
fprintf(stderr, "Error %s: %d\n", action, GetLastError());
exit(EXIT_FAILURE);
}
 
COORD coord={0,0}; // this is global variable
//center of axis is set to the top left cornor of the screen
void gotoxy(int x,int y)
{
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
void loop1(void *param)
{
 
for(i=0;i<10;i++)
{
 
gotoxy(0,i+3);printf("first thread\n");
Sleep(1000);
}
 
_endthread();
}
 
void loop2(void *param)
{
 
for(j=0;j<10;j++)
{
gotoxy(15,j+3);printf("second thread\n");
Sleep(1000);
}
 
_endthread();
}
int main()
{
int k;
HANDLE loop_thread[2];
loop_thread[0] = (HANDLE) _beginthread( loop1,0,NULL);
if (loop_thread[0] == INVALID_HANDLE_VALUE)
error("creating read thread");
 
loop_thread[1] = (HANDLE) _beginthread( loop2,0,NULL);
if (loop_thread[1] == INVALID_HANDLE_VALUE)
error("creating write thread");
 
WaitForMultipleObjects(2, loop_thread, TRUE, INFINITE);
 
 
return 0;
}


In this program two loops run in same time printing the message by creating multiple threads.I have used gotoxy(int,int) to prevent overlapping the first loop output by second loop output.

2 comments:

  1. Hi very interesting... but while I know ANSI C I do not understand the symbols and the types of variables you use... For example taking one row each time from your code what is the HANDLE type... I have never saw it..

    ReplyDelete