Search code examples
cwindowsmultiprocessingsapi

Multiprocessing in 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);
    }
}

Solution

  • 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.)