创建时如何设置pthread名称?
How to set pthread name at the time of creation?
我在我的程序中使用 pthread。使用 pthread_create() 创建。创建后我正在使用 pthread_setname_np() 来设置创建的线程的名称。
我观察到我设置的名称需要一点时间才能反映出来,最初线程继承了程序名称。
有什么建议可以在我使用 pthread_create() 创建线程时设置线程名称吗?我在可用的 pthread_attr() 中进行了一些研究,但没有找到有用的函数。
重现我观察到的内容的快速方法如下:
void * thread_loop_func(void *arg) {
// some code goes here
pthread_getname_np(pthread_self(), thread_name, sizeof(thread_name));
// Output to console the thread_name here
// some more code
}
int main() {
// some code
pthread_t test_thread;
pthread_create(&test_thread, &attr, thread_loop_func, &arg);
pthread_setname_np(test_thread, "THREAD-FOO");
// some more code, rest of pthread_join etc follows.
return 0;
}
输出:
<program_name>
<program_name>
THREAD-FOO
THREAD-FOO
....
我正在寻找反映 THREAD-FOO 的第一个控制台输出。
how I can set the thread name at the time I create the thread using pthread_create()?
那是不可能的。相反,您可以使用屏障或互斥锁来同步子线程,直到它准备好 运行。或者您可以从线程内部设置线程名称(如果任何其他线程未使用它的名称)。
请勿使用pthread_setname_np
。这是一个非标准的 GNU 扩展。 _np
后缀的字面意思是“不可移植”。编写可移植代码,而不是使用您自己的线程名称存储位置。
我在我的程序中使用 pthread。使用 pthread_create() 创建。创建后我正在使用 pthread_setname_np() 来设置创建的线程的名称。
我观察到我设置的名称需要一点时间才能反映出来,最初线程继承了程序名称。
有什么建议可以在我使用 pthread_create() 创建线程时设置线程名称吗?我在可用的 pthread_attr() 中进行了一些研究,但没有找到有用的函数。
重现我观察到的内容的快速方法如下:
void * thread_loop_func(void *arg) {
// some code goes here
pthread_getname_np(pthread_self(), thread_name, sizeof(thread_name));
// Output to console the thread_name here
// some more code
}
int main() {
// some code
pthread_t test_thread;
pthread_create(&test_thread, &attr, thread_loop_func, &arg);
pthread_setname_np(test_thread, "THREAD-FOO");
// some more code, rest of pthread_join etc follows.
return 0;
}
输出:
<program_name>
<program_name>
THREAD-FOO
THREAD-FOO
....
我正在寻找反映 THREAD-FOO 的第一个控制台输出。
how I can set the thread name at the time I create the thread using pthread_create()?
那是不可能的。相反,您可以使用屏障或互斥锁来同步子线程,直到它准备好 运行。或者您可以从线程内部设置线程名称(如果任何其他线程未使用它的名称)。
请勿使用pthread_setname_np
。这是一个非标准的 GNU 扩展。 _np
后缀的字面意思是“不可移植”。编写可移植代码,而不是使用您自己的线程名称存储位置。