Skip to content

Instantly share code, notes, and snippets.

@armadillu
Created August 8, 2017 22:33
Show Gist options
  • Save armadillu/c7337cc8433bffe318d1266d126522f6 to your computer and use it in GitHub Desktop.
Save armadillu/c7337cc8433bffe318d1266d126522f6 to your computer and use it in GitHub Desktop.
ofThread crash test
#include "ofApp.h"
int main() {
ofSetupOpenGL(1024, 768, OF_WINDOW);
ofRunApp(new ofApp());
}
#include "ofApp.h"
void ofApp::setup(){
}
void ofApp::createThread(int n){
for(int i = 0; i < n; i++){
#if USE_OF_THREAD
ThreadTest * t = new ThreadTest();
threads.push_back(t);
t->startThread();
#else
ThreadTest * t = new ThreadTest();
if(t){
t->thread.detach();
}else{
ofLogError("ofApp") << "cant detaqch this std::thread!";
}
threads.push_back(t);
#endif
numThreadsCreated++;
}
}
void ofApp::update(){
float dt = 1./60.;
createThread(4); //spawn N threads per frame
int index = threads.size() -1;
for(int i = index; i >= 0; i--){
#if USE_OF_THREAD
ThreadTest * t = threads[i];
if(!t->isThreadRunning()){
if(t->getNativeThread().get_id() == std::thread::id()){
delete t; //OK!
}else{
ofLogError("ofApp") << "ofThread is done but we will crash if we try to delete - LEAKING";
leakedThreads.push_back(t);
}
threads.erase(threads.begin() + i);
}
#else
ThreadTest * t = threads[i];
if(t->done == true){
if(t->thread.get_id() == std::thread::id()){
delete t; //OK!
}else{
ofLogError("ofApp") << "std::thread is done but we will crash if we try to delete - LEAKING";
leakedThreads.push_back(t);
}
threads.erase(threads.begin() + i);
}
#endif
}
}
void ofApp::draw(){
string msg =
"Using " + string(USE_OF_THREAD ? "ofThread" : "std::thread") +
"\nnumThreadsCreated=" + ofToString(numThreadsCreated) +
"\nNumThreadsAlive=" + ofToString(threads.size()) +
"\nNumLeakedThreads=" + ofToString(leakedThreads.size());
ofDrawBitmapStringHighlight(msg, 30, 30);
}
#pragma once
#include "ofMain.h"
#define USE_OF_THREAD true
//////////////////////////////////////////////////////////////////////////////////////
#if USE_OF_THREAD
class ThreadTest : public ofThread{
public:
void threadedFunction(){
//ofSleepMillis(1);
}
};
#else
class ThreadTest{
public:
std::thread thread;
std::atomic<bool> done;
ThreadTest() : done(false) {
thread = std::thread(&ThreadTest::threadedFunction, this);
}
void threadedFunction(){
//ofSleepMillis(1);
done = true;
}
};
#endif
//////////////////////////////////////////////////////////////////////////////////////
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
vector<ThreadTest*> threads;
vector<ThreadTest*> leakedThreads;
int numThreadsCreated = 0;
void createThread(int n);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment