gpt4 book ai didi

C - 线程函数 : Casting a (void*) to a (long) and code works? 但是如何呢?

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:25 26 4
gpt4 key购买 nike

<分区>

下面的函数 printHello 接收一个空指针 作为参数。 但是这个指针被强制转换为 long 并且代码有效。我不认为我理解这种转换是如何工作的。指针类型不应该保存地址吗?long 类型如何突然兼容转换为指针类型,反之亦然?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define NUM_OF_THREADS 5

void *printHello (void *thread_id)
{
long tid;
tid = (long) thread_id; // Why is this possible?
printf("hello from thread #%ld!", tid);
pthread_exit(NULL);
}

int main()
{
pthread_t threads[NUM_OF_THREADS];
int return_code;
long i;

for(i=0; i<NUM_OF_THREADS; i++)
{
printf("In main: creating thread %ld\n", i);

return_code = pthread_create(&threads[i],NULL,printHello,(void*) i);
// Why does it allow to cast 'long i' into '(void*) i'?

if(return_code)
{
printf("Error: return code from pthread_create is %d\n", return_code);
exit(-1);
}
}
pthread_exit(NULL);
}

示例输出:

In main: creating thread 0
In main: creating thread 1
hello from thread #0!
hello from thread #1!
In main: creating thread 2
In main: creating thread 3
hello from thread #2!
In main: creating thread 4
hello from thread #3!
hello from thread #4!

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com