ofThread consumes 100% CPU usage

Hi, I’m trying to use ofThread but it is really expensive just for using the empty while loop in the threaded function.

Here’s my code.

Everything in ofApp.h and nothing in ofApp.cpp

#pragma once

#include "ofMain.h"

class myThread : public ofThread {
    void threadedFunction()
        while (isThreadRunning()) {

class ofApp : public ofBaseApp{
		void setup();
		void update();
		void draw();
		void keyPressed(int key);
		void keyReleased(int key);
		void mouseMoved(int x, int y);
		void mouseDragged(int x, int y, int button);
		void mousePressed(int x, int y, int button);
		void mouseReleased(int x, int y, int button);
		void mouseEntered(int x, int y);
		void mouseExited(int x, int y);
		void windowResized(int w, int h);
		void dragEvent(ofDragInfo dragInfo);
		void gotMessage(ofMessage msg);

    myThread thread;

When I run this code, the CPU is over 100%.
Is it normal? I’m using OF v0.9.8 on Mac OS X 10.11.6.
Any advise or guidance would be greatly appreciated!

Hi! Just guessing here, but could it be that the empty while loop is like an infinite loop? Maybe sleeping a bit helps? :slight_smile: See http://openframeworks.cc/documentation/utils/ofThread/#show_sleep

Update: from that document:

If the user does not give the thread a chance to sleep, the thread may take 100% of the CPU core while it’s looping as it waits for something to do. This may lead to poor application performance.

1 Like

hey yes if you just have a while loop it’ll run as fast as possible and even if it’s only checking isThreadRunning it’s checking it as much as it can using a full cpu. as @hamoid says you usually sleep a bit between loop cycles or even better use a thread channel so the thread only wakes up when there’s data to process

1 Like

That makes sense. I decided to use a thread channel. Thank you so much guys!