gpt4 book ai didi

c - lpthread:编译时警告,执行时奇怪的结果

转载 作者:行者123 更新时间:2023-11-30 20:38:13 31 4
gpt4 key购买 nike

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

#define NB_THREAD 2
void *func(void *arg){
printf("thread %d \n ",(int) (int*)arg);
}
int main(int argc, char *argv[])
{
int i, status;
pthread_t tid [NB_THREAD];
for(i=0;i<NB_THREAD; i++)
{
if(pthread_create(&tid[i], NULL, func, argv[i+1])!=0){
printf("error thread create \n "); exit(1);
}
}
for(i=0;i<NB_THREAD; i++)
{
if(pthread_join(tid[i],(void**)status)!=0){
printf("error thread join \n"); exit(1);
}
else
printf("thread success \n");
}
return 0;
}


gcc -std = c99 test.c -o test -lpthread

test.c: In function ‘func’:
test.c:8:25: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
printf("thread %d \n ",(int) (int*)arg);
^
test.c: In function ‘main’:
test.c:22:26: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
if(pthread_join(tid[i],(void**)status)!=0){


有人可以向我解释吗?


>在我的终端中得到以下结果:

>螺纹-649483154
>线程0
>线程成功
>线程成功

最佳答案

您的问题似乎是func()处理arg的方式...您将其强制转换为指向int的指针,然后将其强制转换为int ...您是否正在尝试打印出arg+1的“地址”(从main的角度来看),还是您尝试打印其值... ???

这是您的程序的稍作修改的版本,它同时打印出地址和“字符串”值...请注意,将其编译并运行如下:


  ./test你好


#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

#define NB_THREAD 2
void *func(void *arg){
printf("thread %p (-->%s<--)\n", arg, (char*)arg);
}

int main(int argc, char *argv[])
{
int i, status;
pthread_t tid [NB_THREAD];

for(i=0;i<NB_THREAD; i++)
{
if(pthread_create(&tid[i], NULL, func, argv[i+1])!=0){
printf("error thread create \n "); exit(1);
}
}
for(i=0;i<NB_THREAD; i++)
{
if(pthread_join(tid[i],(void**)status)!=0){
printf("error thread join \n"); exit(1);
}
else
printf("thread sucess \n");
}
return 0;
}

关于c - lpthread:编译时警告,执行时奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30146903/

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