ofThread doesn't stop running?

Hello forum !

I just wanna know how to stop a thread when I call ofSystem ‘say’ command ?

The following code works for the first word (Based on the “systemSpeakExample”), but it freeze for the next word because it “cannot start, thread already running”

class Text: public ofThread{
public:
    
    bool bFirst;
    string typeStr, command;
    
    ofTrueTypeFont courierNew;
    
    void setup(){
        ofTrueTypeFont::setGlobalDpi(72);
        
        courierNew.load("Courier New.ttf", 14, true, true);
        courierNew.setLineHeight(13.0f);
        courierNew.setLetterSpacing(1.035);
        
        bFirst  = true;
        typeStr = "";
    }
    
    void draw(){
        if(isThreadRunning()){ // just to see thread running
            ofSetColor(255, 123, 23);
            ofDrawCircle(500, 500, 100);
        }
        ofSetColor(0,255,0);
        courierNew.drawString(typeStr + (ofGetElapsedTimeMillis()/200 % 2 == 0 ? "_" : ""), 10 , 30);
    }
    
    void keyPressed(int key){
        if(key == OF_KEY_DEL || key == OF_KEY_BACKSPACE){
            typeStr = typeStr.substr(0, typeStr.length()-1);
            command = command.substr(0, command.length()-1);
        }
        else if(key == OF_KEY_RETURN ){
            typeStr += "\n";
            startThread();
        }
        else if ((key >= ' ') && (key <= OF_KEY_DEL)){
            
            if( bFirst ){
                typeStr.clear();
                bFirst = false;
            }
            ofUTF8Append(typeStr,key);
            ofUTF8Append(command,key);
        }
    }
    
    void threadedFunction(){
        
        while(isThreadRunning()){
            // call the system command say
            string cmd = "say " + command + " "; // create the command
            
            // print command and execute it
            cout << cmd << endl;
            ofSystem(cmd.c_str());
        }
    }
};

Thank’s

Hi there.

To me using ofThread might be overkill for this type of use case.
If you just want the ofSystem call to not lock the main thread you can do the following:

string cmd = "say " + command + " &";
ofSystem(cmd.c_str());

That will return instantly and you could call it inside of ofApp::keyPressed where you are calling startThread().

Stopping the thread will be tricky in your above scenario because the ofSystem call will block until its finished, so I don’t think it would make much difference to call stopThread as it couldn’t stop it until the system command was finished.

Hope that helps!
Theo

that helps a lot !
it absolutely do the tricks…

thank you !

1 Like