start.cc (1177B)
1 #include "thread" 2 #include "profiler/profiler" 3 4 void Thread::start() { 5 PROFILE ("Thread::start"); 6 7 if (config.foregroundmode()) 8 _run ((void*)this); 9 else { 10 pthread_t th; 11 pthread_attr_t attr; 12 int res; 13 14 if (pthread_attr_init (&attr)) 15 throw Error("Cannot initialize thread attributes"); 16 if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED)) 17 throw Error("Cannot set thread state as detached"); 18 for (int i = 0; i < 3; i++) { 19 # ifdef MISTRUST_THREAD_CREATE_THREADSAFE 20 mutex_lock((void*)_run); 21 # endif 22 res = pthread_create (&th, &attr, _run, (void*) this); 23 # ifdef MISTRUST_THREAD_CREATE_THREADSAFE 24 mutex_unlock((void*)_run); 25 # endif 26 if (!res) { 27 pthread_attr_destroy (&attr); 28 return; 29 } else if (res == EAGAIN) { 30 if (config.verbose()) 31 msg ("Failed to start thread: " + (string)strerror(res) + 32 ", retrying\n"); 33 sleep (1); 34 continue; 35 } else { 36 pthread_attr_destroy (&attr); 37 throw Error(string("Failed to start thread: ") + 38 strerror(res)); 39 } 40 } 41 42 throw Error("Failed to start thread: " 43 "Resources unavailable after 3 tries, giving up"); 44 } 45 }