阅读 LLNL 的 pthread 教程 时,我遇到了以下示例代码
/******************************************************************************
* FILE: hello.c
* DESCRIPTION:
* A "hello world" Pthreads program. Demonstrates thread creation and
* termination.
* AUTHOR: Blaise Barney
* LAST REVISED: 08/09/11
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
我可以理解为什么要通过void *
将long
强制转换(如果不这样做,并且您传递指向t
的指针,则线程打印出的数字会混乱),我的问题是,这是否应该被认为是合法的并且总是有效?还是这只是快速实现线程最简单示例的hack方法?这是一种标准的C语言方法吗?
intptr_t
和uintptr_t
来说,它们并不是未定义的 :-) - obataku整数可以转换为任何指针类型。
/--/……结果是实现定义的,可能不正确对齐,可能不指向引用类型的实体,并且可能是陷阱表示。
在实践中,可以相当安全地依赖于这种实现定义的行为:long 可能足够大以容纳地址,并且我想不出会导致陷阱表示的任何平台。只有在尝试通过指针访问内存时才存在对齐问题。 - Lundin