【发布时间】:2020-11-10 04:52:41
【问题描述】:
我想根据用户希望创建的数量生成多个线程,每个线程都执行一个函数“readFiles”。但是,在线程可以分别执行 readFiles 中的任何有意义的代码(由 "..." 表示)之前,我希望所有线程都在一种介绍性通知消息中打印出它们的线程 ID,所以像......
"Thread ID _____ is processing!"
"Thread ID _____ is processing!"
"Thread ID _____ is processing!"
...
...
...
...但显然,对于我拥有的代码,每个线程一次只运行一个,因此线程 ID 仅在每个新线程开始执行有意义的代码时打印出来,所以这...
"Thread ID _____ is processing!"
...
"Thread ID _____ is processing!"
...
"Thread ID _____ is processing!"
...
在我对每个特定的新线程调用 pthread_create() 之前,有没有办法获取线程 ID?或者有没有一种方法可以让这些线程(它们应该同时运行),推迟或暂停它们在 readFiles (它们的 "..." )中执行有意义的代码,直到它们各自打印出首先是线程 ID 消息?非常感谢大家!!!这是我的代码,可让您更好地了解我目前拥有的内容...
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
uint64_t gettid()
{
pthread_t actual_tid = pthread_self();
uint64_t threadId = 0;
memcpy( &threadId, &actual_tid, sizeof( actual_tid ) );
return threadId;
}
void *readFiles( void *args )
{
pthread_mutex_lock(&mutex);
uint64_t current_id = gettid();
printf("Thread id = ");
printf("%" PRIu64 , current_id );
...
...
...
pthread_mutex_unlock(&mutex);
}
void alphabetcountmulthreads(int num_threads)
{
pthread_t ids[num_threads];
for ( int t = 0; t < num_threads; t++ )
{
if ( pthread_create( &ids[t], NULL, &readFiles, NULL ) != 0 )
{
fprintf( stderr, "error: Cannot create thread # %d\n", t );
break;
}
}
for ( int u = 0; u < num_threads; ++u )
{
if ( pthread_join( ids[u], NULL ) != 0 )
{
fprintf( stderr, "error: Cannot join thread # %d\N", u );
}
}
}
【问题讨论】:
标签: c linux pthreads posix pthread-join