#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){
请问有人向我解释一下吗?
答案 0 :(得分:0)
您的问题似乎是func()处理arg的方式...您将它转换为指向int的指针,然后将其转换为int ...您是否正在尝试打印&#34;地址& #34;是arg+1
(来自main
的观点),还是你试图打印出它的价值...... ???
这是程序的略微修改版本,它打印出地址和&#34;字符串&#34;值...注意,编译并运行如下:
./在那里测试你好
#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;
}