Multiprocessing in C - c

I once watched a movie called "War Games". I wanted to emulate that program in the movie. I wrote a simple program that can print and then speak the sentence, or the other way around. I want the program to execute both at the same time. How do I do that?
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <Windows.h>
#include <sapi.h>
ISpVoice *pVoice = NULL;
void printSmoothly(wchar_t *Str);
int main(void)
{
if (FAILED(::CoInitialize(NULL)))
return FALSE;
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL,
IID_ISpVoice, (void **)&pVoice);
wchar_t *sentence = L"Greetings professor falken,What would you like to do ?";
// how can i execute these two at the same time ?
printSmoothly(sentence);
pVoice->Speak(sentence, 0, NULL);
pVoice->Release();
CoUninitialize();
return 0;
}
void printSmoothly(wchar_t *Str)
{
size_t len = wcslen( Str ) , n ;
for( n = 0 ; n < len ; n++ )
{
wprintf( L"%c", Str[n] );
Sleep(50);
}
}

You want the speaking to be asynchronous.
Fortunately, Speak has a flag for that, so you don't need to dig into multiprocessing yet:
pVoice->Speak(sentence, SPF_ASYNC, NULL);
printSmoothly(sentence);
Note that you need to start the speech first, or it won't start until the printing has finished.
You'll also need to take care that you don't Release and CoUninitialize until the speaking has finished.
This will happen if you print faster than the speech, for instance.
(Asynchronous programming is much harder in reality than it is in Hollywood.)

Related

problems utilitizing small pauses in c code using nanosleep

I am a C beginner and trying this and that.
I want to display a string letter by letter with tiny pauses in between. So my idea was a small pause using sleep or usleep after displaying each char but I read that using nanosleep in your own function makes more sense. So I put my little pauses in a function "msleep" to get microseconds pauses.
I output my string 3 times.
Once in the main(), then in a do-while-loop in a function (fancyOutput) char by char, and eventually in the same function with printf again to check, if it was handled over correctly.
My problem: I expected, that the middle output would work char by char and separated by 100/1000 seconds breaks, but what I experience is a long break before chowing any char and then a fast output if line two and three. It looks like the compiler "realized what I am planning to do and wants to modify the code to be more efficient." So all my pauses seemed to be combined in one long break.
Maybe you remeber the captions in the tv series "x files" - something like that I want to produce.
For sure there are better and more sophisticated ways to archieve what I am going to try but I want to learn and understand what is going on. Can someone help me with that?
I am using codeclocks on a debian-based distro with gcc.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
You are getting problem with buffer.
When you use printf with no \n (new line) C is buffering the display in order to display information block by block (to optimize displaying speed).
Then you need to either add a \n to your printf or add a flush of the stdout.
An other solution will be to use stderr, which got no buffer, but stderr is meant for error not output :)
You can also check setvbuf in order to change the buffering.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
flush(stdout);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
So, I tried the solution to place fflush(stdout); directly after the char-output in the loop. It worked as intended.
Summarizing for those with similar problems (guess this also happens with usleep and similar self-made functions):
As I understaood, printf "collects" data in stdout until it "sees" \n, which indicates the end of a line. Then printf "releases" stdout. So in my initial post it "kept" each single char in stdout, made a pause after each char and finally released stdout in one fast output.
So fflush(stdout); after each char output via empties stdout char by char.
Hope it can help others.

C sleep method obstructs output to console

I have a C program, where I just wanted to test if I could reproduce a console spinner used in npm install while it installs a module. This particular spinner simply spins in this order:
|
/
-
\
on the same space, so I use the following program:
#include <stdio.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
// \b is to make the character print to the same space
printf("\b%c", sequence[i]);
// now I want to delay here ~0.25s
}
}
}
So I found a way to make it rest for that long from <time.h> documentation and made this program:
#include <stdio.h>
#include <time.h>
void sleep(double seconds) {
clock_t then;
then = clock();
while(((double)(clock() - then) / CLOCKS_PER_SEC) < seconds); //do nothing
}
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
sleep(0.25);
}
}
}
But now nothing prints to the console. Does anyone know how I can go about producing the behavior I want?
EDIT According to what appears to be popular opinion, I've updated my code above to be the following:
#include <stdio.h>
#include <unistd.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
/* fflush(stdout); */
// commented out to show same behavior as program above
usleep(250000); // 250000 microseconds = 0.25 seconds
}
}
}
You will need to flush after you wrote to the console. Otherwise, the program will buffer your output:
fflush(stdout);
Things do get printed to console, it's just does not get flushed. Add fflush(stdout) to see the results, or set the console in an unbuffered mode by calling setbuf:
setbuf(stdout, NULL);
A bigger problem with your code is that your sleep method runs a busy loop, which burns CPU cycles for no good reason. A better alternative would be to call usleep, which takes the number of microseconds:
usleep(25000);
The sleep function isn't really your problem. The issue is that the output is buffered. The simplest thing to do will be to research ncurses.
For now:
fflush(stdout);

Thread Programming... No output in terminal

I m doing thread programming and trying to implement MonteCarlo technique for calculating Pi value in it. I compiled the code and I have no error but when I execute I get no output for it. Kindly correct me if there's any mistake.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define frand() ((double) rand() / (RAND_MAX))
#define MAX_LEN 1353
const size_t N = 4;
float circlePoints=0;
void* point_counter(void *param){
float xcord;
float ycord;
while(MAX_LEN){
xcord=frand();
ycord=frand();
float cord = (xcord*xcord) + (ycord*ycord);
if(cord <= 1){
circlePoints++;}
}
}
int main()
{
printf("out");
size_t i;
pthread_t thread[N];
srand(time(NULL));
for( i=0;i <4;++i){
printf("in creating thread");
pthread_create( &thread[i], NULL, &point_counter, NULL);
}
for(i=0;i <4;++i){
printf("in joining thread");
pthread_join( thread[i], NULL );
}
for( i=0;i <4;++i){
printf("in last thread");
float pi = 4.0 * (float)circlePoints /MAX_LEN;
printf("pi is %2.4f: \n", pi);
}
return 0;
}
You're hitting an infinite loop here:
while(MAX_LEN){
Since MAX_LEN is and remains non-zero.
As to why you see no output before that, see Why does printf not flush after the call unless a newline is in the format string?
You have an infinite loop in your thread function:
while(MAX_LEN){
...
}
So all the threads you create never come out that loop.
Also, circlePoints is modified by all the threads which will lead to race condition ( what's a race condition? ) and likely render the value incorrect. You should use a mutex lock to avoid it.
while(any_non_zero_number_which does_not_update)
{
infinite loop //not good unless you intend it that way
}

How to stop a specific thread in C process.h?

I just learn the bare bone of making a thread inside a program using process.h in C programming. And now, my problem is how to stop a specific thread.
Here is my code:
#include <stdio.h>
#include <windows.h>
#include <process.h>
void mimicCounter( void * );
int main()
{
int i;
printf( "Now in the main() function.\n" );
_beginthread( mimicCounter, 0, (void*)12 );
for(i = 2; i <= 10; i++){
Sleep(500);
printf("%d\n",i);
}
system("PAUSE");
printf("\n");
}
void mimicCounter( void *arg )
{
int i;
printf( "The mimicCounter() function was passed %d\n", (INT_PTR)arg ) ;
for(i = 1; i <= 10; i++){
Sleep(500);
printf("%d\n",i);
}
}
I just want to stop the thread that I have created (the mimicCounter function) when it reaches i = 5, (yeah I know I set it to 10 but this is for ending a thread demo).
Thank you so much :)
The _endthread and _endthreadex functions terminate a thread created by _beginthread or _beginthreadex, respectively. You can call _endthread or _endthreadex explicitly to terminate a thread; however, _endthread or _endthreadex is called automatically when the thread returns from the routine passed as a parameter to _beginthread or _beginthreadex. Terminating a thread with a call to endthread or _endthreadex helps to ensure proper recovery of resources allocated for the thread.
From http://msdn.microsoft.com/en-us/library/aa246804(v=vs.60).aspx

Multithreading - C - Duplicate Static Variable

is there anyway to duplicate some static variable each time a thread make access to them?
I post a simple example:
Module testF.c
#define <stdio.h>
#include <windows.h>
#include <process.h>
#include "testF.h"
#define MAX_THREADS 10
int *var;
void testF( void *arg ){
int a,N,i;
a = (INT_PTR)arg;
N = (int)(10000/(int)(a+1));
var = (int*) malloc(N*sizeof(int));
for(i = 0; i<N; i++)
var[i] = (int)a;
_endthread();
}
...
And in another module main.c,
...
#include "testF.h"
int main(void){
HANDLE hth[MAX_THREADS];
DWORD dwExitCode;
int i;
for(i = 0; i<MAX_THREADS; i++)
hth[i] = (HANDLE)_beginthread( testF, 0, (void*)i );
WaitForMultipleObjects(MAX_THREADS, hth, TRUE, INFINITE);
for(i = 0; i<MAX_THREADS; i++){
GetExitCodeThread( hth[i], &dwExitCode );
printf( "thread 1 exited with code %u\n", dwExitCode );
CloseHandle( hth[i] );
}
}
In the this example the variable i would like to duplicate is *var.
I've seen that functions like rand() give always the same result if called from different thread, so I think that there should be a way to do it.
Thread-local storage.
Functions like rand() generally use thread local storage to maintain intercall state on a per-thread basis. This is what you would need to do instead of using a language construct like static. Your other option is to supply the variable into the thread start function, instead of using a global or static.

Resources