【发布时间】:2014-01-07 15:43:22
【问题描述】:
这是代码的sn-p。我可以设置线程的名称。但是,在检索线程名称时出现错误。请帮忙。
void *Thread_Function_A(void *thread_arg)
{
char buf[7];
int rc;
pthread_t self;
self = pthread_self ();
rc = pthread_getname_np(self, buf,7);
if ( rc != 0 )
cout<<"Failed getting the name"<<endl;
}
int main(int argc, char *argv[])
{
int rc;
pid_t thread_pid_val = getpid();
thread_1.create_thread((thread_1.get_thread_id()), NULL,Thread_Function_A,&thread_pid_val);
thread_2.create_thread((thread_2.get_thread_id()), NULL,Thread_Function_A,&thread_pid_val);
rc = pthread_setname_np(*(thread_1.get_thread_id()), "Thread_A");
if( rc != 0)
{
cout<<"Setting name for thread A failed"<<endl;
}
rc = pthread_setname_np(*(thread_2.get_thread_id()), "Thread_B");
if( rc != 0)
{
cout<<"Setting name for thread B failed"<<endl;
}
pthread_join( *(thread_1.get_thread_id()), NULL);
pthread_join( *(thread_2.get_thread_id()), NULL);
return 0;
}
输出:-
$./thread_basic.out
Failed getting the nameFailed getting the name
The name of thread is The name of thread is
strerror 说 - 数值结果超出范围 错误=34
现在添加了完整的代码。在这里,我没有设置正确的名称。相反,它检索程序的名称。
void *Thread_Function_A(void *thread_arg)
{
char name[300];
char buf[200];
int rc;
char message[100];
FILE *fp;
pthread_t self;
self = pthread_self ();
rc = pthread_getname_np(self, buf,200);
if ( rc != 0 )
{
cout<<"Failed getting the name"<<endl;
cerr<<"Pthread get name error ="<<rc<< " " << strerror(rc) << endl;
}
sprintf(name,"log_%s.txt",buf);
cout<<"The name of thread is "<<buf<<endl;
fp = fopen(name,"w+");
for( int i = 1; i<=5; i++)
{
sprintf(message,"The thread id is %d and value of i is %d",pthread_self(),i);
fprintf(fp,"%s\n", message);
fflush(fp);
/** local variable will not be shared actually**/
/** each thread should execute the loop for 5 **/
/** total prints should be 10 **/
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int rc;
pthread_t threadA, threadB;
pid_t thread_pid_val = getpid();
thread_1.create_thread(&threadA, NULL,Thread_Function_A,&thread_pid_val);
thread_1.set_thread_id(threadA);
rc = pthread_setname_np(threadA, "Thread_A");
if( rc != 0)
{
cout<<"Setting name for thread A failed"<<endl;
}
thread_2.create_thread(&threadB, NULL,Thread_Function_A,&thread_pid_val);
thread_2.set_thread_id(threadB);
rc = pthread_setname_np(threadB, "Thread_B");
if( rc != 0)
{
cout<<"Setting name for thread B failed"<<endl;
}
pthread_join( threadA, NULL);
pthread_join( threadB, NULL);
return 0;
}
输出如下。
]$ ./thread_basic.out
The name of thread is thread_basic.ou
The name of thread is Thread_B
【问题讨论】:
-
如果您阅读manual page,您将看到该函数返回错误号(而不是在
errno中设置它),您可能希望打印该错误号(或者使用@987654322 打印可打印字符串@)。 -
数值结果超出范围是错误。
-
阅读我在之前评论中链接到的手册页。
-
此外,这里还有一个竞争条件:如果线程在开始线程有机会分配名称之前到达对
pthread_getname_np的调用,那该怎么办?
标签: c++ linux multithreading linux-kernel pthreads