#include "thread"
#include "profiler/profiler"

void Thread::start() {
    PROFILE ("Thread::start");
    
    if (config.foregroundmode())
	_run ((void*)this);
    else {
	pthread_t th;
	pthread_attr_t attr;
	int res;

	if (pthread_attr_init (&attr))
	    throw Error("Cannot initialize thread attributes");
	if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED))
	    throw Error("Cannot set thread state as detached");
	for (int i = 0; i < 3; i++) {
#	    ifdef MISTRUST_THREAD_CREATE_THREADSAFE
	    mutex_lock((void*)_run);
#	    endif	    
	    res = pthread_create (&th, &attr, _run, (void*) this);
#	    ifdef MISTRUST_THREAD_CREATE_THREADSAFE
	    mutex_unlock((void*)_run);
#	    endif	    
	    if (!res) {
		pthread_attr_destroy (&attr);
		return;
	    } else if (res == EAGAIN) {
		if (config.verbose())
		    msg ("Failed to start thread: " + (string)strerror(res) +
			 ", retrying\n");
		sleep (1);
		continue;
	    } else  {
		pthread_attr_destroy (&attr);
		throw Error(string("Failed to start thread: ") +
			    strerror(res));
	    }
	}
		
	throw Error("Failed to start thread: "
		    "Resources unavailable after 3 tries, giving up");
    }
}
