static void tc_pthread_pthread_setgetname_np(void) { int ret_chk; pthread_t name_th; char *thread_name = "NameThread"; char get_name[32]; ret_chk = pthread_create(&name_th, NULL, setgetname_thread, NULL); TC_ASSERT_EQ("pthread_create", ret_chk, OK); ret_chk = pthread_setname_np(name_th, "NameThread"); TC_ASSERT_EQ("pthread_setname_np", ret_chk, OK); ret_chk = pthread_getname_np(name_th, get_name); TC_ASSERT_EQ("pthread_getname_np", ret_chk, OK); TC_ASSERT_EQ("pthread_getname_np", strcmp(get_name, thread_name), 0); ret_chk = pthread_cancel(name_th); TC_ASSERT_EQ("pthread_cancel", ret_chk, OK); ret_chk = pthread_join(name_th, NULL); TC_ASSERT_EQ("pthread_join", ret_chk, OK); TC_SUCCESS_RESULT(); }
/* ======================== Sys_DestroyThread ======================== */ void Sys_DestroyThread( uintptr_t threadHandle ) { if( threadHandle == 0 ) { return; } char name[128]; name[0] = '\0'; #if defined(DEBUG_THREADS) pthread_getname_np( threadHandle, name, sizeof( name ) ); #endif #if 0 //!defined(__ANDROID__) if( pthread_cancel( ( pthread_t )threadHandle ) != 0 ) { idLib::common->FatalError( "ERROR: pthread_cancel %s failed\n", name ); } #endif if( pthread_join( ( pthread_t )threadHandle, NULL ) != 0 ) { idLib::common->FatalError( "ERROR: pthread_join %s failed\n", name ); } }
bool ksthread_getThreadName(const KSThread thread, char* const buffer, int bufLength) { // WARNING: This implementation is no longer async-safe! const pthread_t pthread = pthread_from_mach_thread_np((thread_t)thread); return pthread_getname_np(pthread, buffer, (unsigned)bufLength) == 0; }
int px4_sem_timedwait(px4_sem_t *s, const struct timespec *abstime) { int ret = pthread_mutex_lock(&(s->lock)); if (ret) { return ret; } s->value--; errno = 0; if (s->value < 0) { ret = pthread_cond_timedwait(&(s->wait), &(s->lock), abstime); } else { ret = 0; } int err = ret; if (err != 0 && err != ETIMEDOUT) { setbuf(stdout, NULL); setbuf(stderr, NULL); const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; (void)pthread_getname_np(pthread_self(), thread_name, NAMELEN); PX4_WARN("%s: px4_sem_timedwait failure: ret: %d, %s", thread_name, ret, strerror(err)); } int mret = pthread_mutex_unlock(&(s->lock)); return (err) ? err : mret; }
void app_print_thread_state(pthread_t threadId) { char namebuf[32]; clockid_t clockId; struct timespec time; int err; (void)err; err = pthread_getcpuclockid(threadId, &clockId); urosAssert(err == 0); err = clock_gettime(clockId, &time); urosAssert(err == 0); memset(namebuf, 0, sizeof(namebuf)); err = pthread_getname_np(threadId, namebuf, 31); urosAssert(err == 0); namebuf[31] = 0; #if PTHREAD_GETNAME_NP_NEWLINE if (strlen(namebuf) >= 2) { namebuf[strlen(namebuf) - 2] = 0; } #endif printf("%lu %lu.%9.9lu %s\n", (unsigned long)threadId, (unsigned long)time.tv_sec, (unsigned long)time.tv_nsec, namebuf); }
static void get_tname(ph_thread_t *me, char *buf, uint32_t size) { uint64_t tid; if (me) { ph_snprintf(buf, size, "%s/%d", me->name, me->tid); return; } #if defined(__linux__) tid = syscall(SYS_gettid); #elif defined(__MACH__) pthread_threadid_np(pthread_self(), &tid); #elif defined(__sun__) tid = _lwp_self(); #else tid = (uint64_t)(intptr_t)self; #endif #if defined(__linux__) || defined(__MACH__) if (pthread_getname_np(pthread_self(), buf, size) == 0) { int len = strlen(buf); if (len > 0) { ph_snprintf(buf + len, size - len, "/%" PRIu64, tid); return; } } #endif ph_snprintf(buf, size, "lwp/%" PRIu64, tid); }
int LqThreadBase::GetName(intptr_t Id, char* DestBuf, size_t Len) { #if !defined(LQPLATFORM_ANDROID) return pthread_getname_np(Id, DestBuf, Len); #else return -1; #endif }
static void dump_threads (void) { MonoThreadInfo *info; MonoThreadInfo *cur = mono_thread_info_current (); MOSTLY_ASYNC_SAFE_PRINTF ("STATE CUE CARD: (? means a positive number, usually 1 or 2, * means any number)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x0\t- starting (GOOD, unless the thread is running managed code)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x1\t- running (BAD, unless it's the gc thread)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x2\t- detached (GOOD, unless the thread is running managed code)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x?03\t- async suspended (GOOD)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x?04\t- self suspended (GOOD)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x?05\t- async suspend requested (BAD)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x?06\t- self suspend requested (BAD)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x*07\t- blocking (GOOD)\n"); MOSTLY_ASYNC_SAFE_PRINTF ("\t0x?08\t- blocking with pending suspend (GOOD)\n"); FOREACH_THREAD_SAFE (info) { #ifdef TARGET_MACH char thread_name [256] = { 0 }; pthread_getname_np (mono_thread_info_get_tid (info), thread_name, 255); MOSTLY_ASYNC_SAFE_PRINTF ("--thread %p id %p [%p] (%s) state %x %s\n", info, (void *) mono_thread_info_get_tid (info), (void*)(size_t)info->native_handle, thread_name, info->thread_state, info == cur ? "GC INITIATOR" : "" ); #else MOSTLY_ASYNC_SAFE_PRINTF ("--thread %p id %p [%p] state %x %s\n", info, (void *) mono_thread_info_get_tid (info), (void*)(size_t)info->native_handle, info->thread_state, info == cur ? "GC INITIATOR" : "" ); #endif } END_FOREACH_THREAD_SAFE }
int main(int argc, char **argv) { pthread_t thread; int rc=0; char theName[16]; pthread_setname_np(thread, "THREADNAMEISTOOLONG"); memset(theName, 0x00, sizeof(theName)); printf("Create thread using the default attributes\n"); rc = pthread_create(&thread, NULL, threadfunc, NULL); if(0 == rc) { rc = pthread_setname_np(thread, "THREADNAMEISTOOLONG"); if(0 == rc) { rc = pthread_getname_np(thread, theName); if(0 == rc) { printf("The thread name is %s.\n", theName); } } rc = pthread_join(thread, NULL); } if(0 != rc) { printf("An error occurred - %d\n", rc); } printf("Main completed\n"); return(rc); }
void safeSend(zmq::socket_t &sock, const char *buf, size_t buflen) { char tnam[100]; int pgn_rc = pthread_getname_np(pthread_self(),tnam, 100); assert(pgn_rc == 0); //if (buflen>10){FileLogger fl(program_name); fl.f() << tnam << " sending " << buf << "\n"; } while (!MessagingInterface::aborted()) { try { zmq::message_t msg(buflen); memcpy(msg.data(), buf, buflen ); sock.send(msg); break; } catch (zmq::error_t) { if (zmq_errno() != EINTR && zmq_errno() != EAGAIN) { { FileLogger fl(program_name); fl.f() << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n"; } if (zmq_errno() == EFSM) { usleep(1000); throw; } usleep(10); continue; } else { std::cerr << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n"; usleep(10); } } } }
int CNIOLinux_pthread_getname_np(pthread_t thread, char *name, size_t len) { #ifdef __ANDROID__ // https://android.googlesource.com/platform/bionic/+/master/libc/bionic/pthread_setname_np.cpp#51 if (thread == pthread_self()) { return TEMP_FAILURE_RETRY(prctl(PR_GET_NAME, name)) == -1 ? -1 : 0; } char comm_name[64]; snprintf(comm_name, sizeof(comm_name), "/proc/self/task/%d/comm", pthread_gettid_np(thread)); int fd = TEMP_FAILURE_RETRY(open(comm_name, O_CLOEXEC | O_RDONLY)); if (fd == -1) return -1; ssize_t n = TEMP_FAILURE_RETRY(read(fd, name, len)); close(fd); if (n == -1) return -1; // The kernel adds a trailing '\n' to the /proc file, // so this is actually the normal case for short names. if (n > 0 && name[n - 1] == '\n') { name[n - 1] = '\0'; return 0; } if (n >= 0 && len <= SSIZE_MAX && n == (ssize_t)len) return 1; name[n] = '\0'; return 0; #else return pthread_getname_np(thread, name, len); #endif }
bool ksmach_getThreadName(const thread_t thread, char* const buffer, size_t bufLength) { // WARNING: This implementation is no longer async-safe! const pthread_t pthread = pthread_from_mach_thread_np(thread); return pthread_getname_np(pthread, buffer, bufLength) == 0; }
std::string mir::test::current_thread_name() { static size_t const max_thread_name_size = 16; char thread_name[max_thread_name_size]; pthread_getname_np(pthread_self(), thread_name, sizeof thread_name); return {thread_name}; }
std::string get_thread_name() { #if !defined(HAVE_NO_THREAD_LOCAL_SUPPORT) return thread_name; #else // This is OSX. Pull the name out of pthreads. char buffer[16]; pthread_getname_np(pthread_self(), buffer, 16); return std::string(buffer, 16); #endif }
char *get_threadname(void) { static char name[32] = ""; #ifndef __APPLE__ prctl(PR_GET_NAME, (unsigned long)name); #else pthread_getname_np(pthread_self(), name, sizeof(name)); #endif return name; }
void *func(void *arg) { pthread_t myId = pthread_self(); char threadName[15]; pthread_getname_np(myId, threadName, 15); while (1) { printf("Thread %s is running\n", threadName); usleep(100000); } }
void get_thread_id(char *buff, int size) { int ret = 1; pthread_t self; self = pthread_self(); #ifdef HAVE_PTHREAD_SET_NAME_NP ret = pthread_getname_np(self, buff, size); if (!ret && !strncmp(buff, program_invocation_short_name, size)) ret = 1; #endif if (ret || !buff[0]) ret = snprintf(buff, size, "%04X", (unsigned) self); }
Optional<std::string> getThreadName(std::thread::id id) { #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME || \ FOLLY_HAS_PTHREAD_SETNAME_NP_NAME std::array<char, kMaxThreadNameLength> buf; if (pthread_getname_np(stdTidToPthreadId(id), buf.data(), buf.size()) != 0) { return Optional<std::string>(); } return folly::make_optional(std::string(buf.data())); #else // There's not actually a way to get the thread name on Windows because // thread names are a concept managed by the debugger, not the runtime. return Optional<std::string>(); #endif }
// one day we should move it to folly/ThreadName.h std::string getThreadName() { #if defined(__GLIBC__) && !defined(__APPLE__) #if __GLIBC_PREREQ(2, 12) char threadName[32]; if (pthread_getname_np(pthread_self(), threadName, sizeof(threadName)) == 0) { return threadName; } #endif #endif return "unknown"; }
bool safeRecv(zmq::socket_t &sock, char *buf, int buflen, bool block, size_t &response_len, int64_t timeout) { char tnam[100]; int pgn_rc = pthread_getname_np(pthread_self(),tnam, 100); assert(pgn_rc == 0); //{FileLogger fl(program_name); fl.f() << tnam << " receiving\n";} response_len = 0; int retries = 5; if (block && timeout == 0) timeout = 500; while (!MessagingInterface::aborted()) { try { zmq::pollitem_t items[] = { { (void*)sock, 0, ZMQ_POLLERR | ZMQ_POLLIN, 0 } }; int n = zmq::poll( &items[0], 1, timeout); if (!n && block) { usleep(10); continue; } if (items[0].revents & ZMQ_POLLIN) { //{FileLogger fl(program_name); fl.f() << tnam << " safeRecv() collecting data\n"; } response_len = sock.recv(buf, buflen, ZMQ_DONTWAIT); if (response_len > 0 && response_len < (unsigned int)buflen) { buf[response_len] = 0; //if (response_len>10){FileLogger fl(program_name); fl.f() << tnam << " saveRecv() collected data '" << buf << "' with length " << response_len << "\n"; } } else { //if (response_len > 10){FileLogger fl(program_name); fl.f() << tnam << " saveRecv() collected data with length " << response_len << "\n"; } } if (!response_len && block) continue; } return (response_len == 0) ? false : true; } catch (zmq::error_t e) { { FileLogger fl(program_name); fl.f() << tnam << " safeRecv error " << errno << " " << zmq_strerror(errno) << "\n"; } if (--retries == 0) { exit(EXIT_FAILURE); } if (errno == EINTR) { std::cerr << "interrupted system call, retrying\n"; if (block) continue; } usleep(10); return false; } } return false; }
void js::ThisThread::GetName(char* nameBuffer, size_t len) { MOZ_RELEASE_ASSERT(len >= 16); int rv = -1; #ifdef HAVE_PTHREAD_GETNAME_NP rv = pthread_getname_np(pthread_self(), nameBuffer, len); #elif defined(__linux__) rv = prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(nameBuffer)); #endif if (rv) nameBuffer[0] = '\0'; }
const char * hts_thread_name(char *buf, size_t len) { #if defined(linux) char tmp[17]; tmp[16] = 0; prctl(PR_GET_NAME, tmp, 0, 0, 0); snprintf(buf, len, "%s", tmp); return buf; #elif defined(APPLE) pthread_getname_np(pthread_self(), buf, len); return buf; #else return "thread-name-unset"; #endif }
void AsyncStream::SendThreadName(void) { ThreadNamePacket packet = {0}; char name[64] = {0}; #if defined(OVR_CAPTURE_ANDROID) char commpath[64] = {0}; sprintf(commpath, "/proc/%d/task/%d/comm", getpid(), gettid()); ReadFileLine(commpath, name, sizeof(name)); #elif defined(OVR_CAPTURE_DARWIN) pthread_getname_np(pthread_self(), name, sizeof(name)); #endif if(name[0]) { WritePacket(packet, name, strlen(name)); } }
void safeSend(zmq::socket_t &sock, const char *buf, size_t buflen, MessageHeader header) { char tnam[100]; int pgn_rc = pthread_getname_np(pthread_self(),tnam, 100); assert(pgn_rc == 0); //if (buflen>10) {FileLogger fl(program_name); fl.f() << tnam << " Sending\n"; } enum send_stage {e_sending_dest, e_sending_source, e_sending_data} stage = e_sending_data; if (header.dest || header.source) { stage = e_sending_source; } while (!MessagingInterface::aborted()) { try { //if (buflen>10){FileLogger fl(program_name); fl.f() << tnam << " safeSend() sending " << buf << "\n"; } if (stage == e_sending_source) { zmq::message_t msg(sizeof(MessageHeader)); memcpy(msg.data(), &header, sizeof(MessageHeader) ); sock.send(msg, ZMQ_SNDMORE); stage = e_sending_data; } if (stage == e_sending_data ) { zmq::message_t msg(buflen); memcpy(msg.data(), buf, buflen ); sock.send(msg); } break; } catch (zmq::error_t) { if (zmq_errno() != EINTR && zmq_errno() != EAGAIN) { { FileLogger fl(program_name); fl.f() << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n"; } if (zmq_errno() == EFSM) throw; usleep(10); continue; } else { { FileLogger fl(program_name); fl.f() << tnam << " safeSend error " << errno << " " << zmq_strerror(errno) << "\n"; } usleep(10); } } } }
void chilog(loglevel_t level, char *fmt, ...) { time_t t; char buf[80], *levelstr; va_list argptr; if(level > loglevel) return; t = time(NULL); strftime(buf,80,"%Y-%m-%d %H:%M:%S",localtime(&t)); switch(level) { case CRITICAL: levelstr = "CRITIC"; break; case ERROR: levelstr = "ERROR"; break; case WARNING: levelstr = "WARN"; break; case INFO: levelstr = "INFO"; break; case DEBUG: levelstr = "DEBUG"; break; case TRACE: levelstr = "TRACE"; break; } /* Get the thread's name. */ char threadname[16]; pthread_getname_np(pthread_self(), threadname, 16); flockfile(stdout); printf("[%s] %6s %s ", buf, levelstr, threadname); va_start(argptr, fmt); vprintf(fmt, argptr); printf("\n"); funlockfile(stdout); va_end(argptr); fflush(stdout); }
bool sendMessage(const char *msg, zmq::socket_t &sock, std::string &response, int32_t timeout_us) { char tnam[100]; int pgn_rc = pthread_getname_np(pthread_self(),tnam, 100); assert(pgn_rc == 0); //NB_MSG << tnam << " sendMessage " << msg << "\n"; safeSend(sock, msg, strlen(msg)); char *buf = 0; size_t len = 0; if (safeRecv(sock, &buf, &len, true, (int64_t)timeout_us)) { response = buf; return true; } return false; }
static void db_log(struct DB *const db, const char *const msg, ...) { if (!db->log) return; const double sec = debug_time_sec(); char th_name[16] = {0}; pthread_getname_np(pthread_self(), th_name, sizeof(th_name)); char head[1024]; char tail[1024]; sprintf(head, "[%-15s|%10s->%10.3lf|%9s] ", th_name, "", sec - db->sec_start, ""); va_list varg; va_start(varg, msg); vsnprintf(tail, sizeof(tail), msg, varg); va_end(varg); fprintf(db->log, "%s%s\n", head, tail); }
static int Sys_GetThreadName( pthread_t handle, char* namebuf, size_t buflen ) { int ret = 0; #ifdef __linux__ ret = pthread_getname_np( handle, namebuf, buflen ); if( ret != 0 ) idLib::common->Printf( "Getting threadname failed, reason: %s (%i)\n", strerror( errno ), errno ); #elif defined(__FreeBSD__) // seems like there is no pthread_getname_np equivalent on FreeBSD idStr::snPrintf( namebuf, buflen, "Can't read threadname on this platform!" ); #endif /* TODO: OSX: // int pthread_getname_np(pthread_t, char*, size_t); */ return ret; }
static ph_thread_t *ph_thread_init_myself(bool booting) { ph_thread_t *me; ck_epoch_record_t *er; er = ck_epoch_recycle(&misc_epoch); if (er) { me = ph_container_of(er, ph_thread_t, epoch_record); } else { me = calloc(1, sizeof(*me)); if (!me) { ph_panic("fatal OOM in ph_thread_init_myself()"); } ck_epoch_register(&misc_epoch, &me->epoch_record); ck_stack_push_mpmc(&ph_thread_all_threads, &me->thread_linkage); ph_counter_init_thread(me); } #ifdef HAVE___THREAD __ph_thread_self = me; #endif pthread_setspecific(__ph_thread_key, me); PH_STAILQ_INIT(&me->pending_nbio); PH_STAILQ_INIT(&me->pending_pool); me->tid = ck_pr_faa_32(&next_tid, 1); me->thr = pthread_self(); #ifdef __sun__ me->lwpid = _lwp_self(); #endif #if defined(__linux__) || defined(__MACH__) // see if we can discover our thread name from the system pthread_getname_np(me->thr, me->name, sizeof(me->name)); #endif // If we were recycled from a non-phenom thread, and are initializing // a non-phenom thread, it is possible that there are still deferred // items to reap in this record, so get them now. if (er && !booting) { ck_epoch_barrier(&misc_epoch, &me->epoch_record); } return me; }
R_API bool r_th_getname(RThread *th, char *name, size_t len) { #if defined(HAVE_PTHREAD_NP) && HAVE_PTHREAD_NP #if __linux__ || __NetBSD__ if (pthread_getname_np (th->tid, name, len) != 0) { eprintf ("Failed to get thread name\n"); return false; } return true; #elif (__FreeBSD__ && __FreeBSD_version >= 1200000) || __DragonFly__ /* || __OpenBSD__ TODO after nxt rel. */ pthread_get_name_np (th->tid, name, len); return true; #else #pragma message("warning r_th_getname not implemented") #endif #else return true; #endif }