1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#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
lock((void*)_run);
# endif
res = pthread_create (&th, &attr, _run, (void*) this);
# ifdef MISTRUST_THREAD_CREATE_THREADSAFE
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");
}
}
|