【发布时间】:2019-12-11 16:09:47
【问题描述】:
我对 C 语言相当陌生,并试图理解线程和指针。据我所知,这一行创建了一个线程
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
第四个参数是指针函数(void *)t的参数,这是一个指向变量t地址的指针,它是long类型?而指针函数将void指针的参数指向一个变量,即(void *)t。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 20
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);
}
之后,我把指针函数和pthread_create改成了这样:
{
long taskid;
sleep(1);
taskid = *(long *)threadid;
printf("Hello from thread %ld\n", taskid);
pthread_exit(NULL);
}
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &t);
那么现在void指针仍然指向变量t的地址?
而*(long *)threadid 正在取消引用变量t?
并在所有线程中输出t的最终值。
我不确定我是否理解正确,如果我在某个地方误解了,我很感激任何建议。我的问题是(void *)t和(void *) &t,它们都是指向变量t的地址的指针,而我读取的指针只能指向地址而不是值,那么为什么(void *)t输出递增t 的值? taskid = *(long *)threadid; 如果我只做taskid = threadid 它会打印出t 的地址,那么*(long *) 会做什么?括号外的* 是取消引用吗?
【问题讨论】:
标签: c multithreading pointers