在64位系统上,指针的大小(通常是8字节)与int的大小(通常是4字节)不同在64位系统上,指针的大小(通常是8字节)与int的大小(通常是4字节)不同指针强制转换为int或从int强制转换为指针时,会导致数据丢失,编译器会发出警告C语言中,可以使用intptr_t或uintptr_t来存储指针的值,这些类型定义在stdint.h头文件中,可以确保指针转换时不会丢失数据
如:
#include <pthread.h>
#include <stdio.h>
#include <stdint.h> // 包含stdint.h头文件
#include <unistd.h>
void *testThread(void *arg) {
uintptr_t arg_value = (uintptr_t)arg; // 使用uintptr_t存储指针值
printf("This is a thread test %ju \n", (uintmax_t)arg_value);
pthread_exit(NULL); // 线程退出
while(1)
{
sleep(1);
}
printf("after pthread exit\n");
return NULL;
}
int main() {
pthread_t tid[5];
int ret;
for (int i = 0; i < 5; i++) { // 修正循环初始化
ret = pthread_create(&tid[i], NULL, testThread, (void *)(uintptr_t)i);
if (ret != 0) {
printf("Error creating thread %d\n", i);
} else {
printf("This is main thread, created thread %d\n", i);
}
}
// 主线程需要等待所有子线程完成
for (int i = 0; i < 5; i++) {
pthread_join(tid[i], NULL);
}
while(1)
{
sleep(1);
}
return 0;
}