#include pthread.h
#include stdio.h
static int seq[50];
void *runner(void *); /* the thread */
int main(int argc, char *argv[])
{
int y;
pthread_t tid[3]; /* the thread identifier */
pthread_attr_t attr; /* set of attributes for the thread */
if(argc!=2)
{
fprintf(stderr,"you need to enter two arguments");
exit(-1);
}
else
{
int a = atoi(argv[1]);
if(a>0)
{
y=a;
}
else
{
fprintf(stderr,"you need to enter a valid number greater than zero");
exit(-1);
}
}
/* get the default attributes */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
/* create three threads */
pthread_create(&tid, NULL, runner,(void *)y);
/* now wait for the thread to exit */
sleep(2);
printf( " Am in main process, The sequence is ");
int j=0,val=0;
for( j = 0; j < 40; j++)
{
val=seq[j];
if(val>=1)
printf( " %d ", seq[j]);
}
pthread_join(tid, NULL);
pthread_exit(0);
}
/**
* The thread will begin control in this function
*/
void *runner(void *param)
{
int count=0;
int y= (int *) param;
// printf(" Am in runner");
while(y!=1)
{
if(y%2==0)
y = y/2;
else
y= ((3*y)+1);
// printf(" %d ", y);
seq[count] = y;
count++;
}
pthread_exit(0);
}
我得到了以下错误
bonus.c: In function ‘main’:
bonus.c:91: warning: cast to pointer from integer of different size
bonus.c:91: warning: passing argument 1 of ‘pthread_create’ from incompatible pointer type
bonus.c:123: warning: passing argument 1 of ‘pthread_join’ makes integer from pointer without a cast
bonus.c: In function ‘runner’:
bonus.c:157: warning: comparison between pointer and integer
bonus.c:159: error: invalid operands to binary %
bonus.c:161: error: invalid operands to binary /
bonus.c:165: error: invalid operands to binary *
bonus.c:171: warning: assignment makes integer from pointer without a cast
发布于 2015-06-27 07:12:32
无论出于什么原因,您都要声明一个pthread_t
数组
pthread_t tid[3];
不要这样做,除非你打算启动三个线程。
你想要的
pthread_t tid;
有两个错误是由此引起的:
pthread_create(&tid, NULL, runner,(void *)y);
(passing argument 1 of ‘pthread_create’ from incompatible pointer type)
其中,传递指向数组的指针而不是指向pthread_t
的指针,以及
pthread_join(tid, NULL);
(passing argument 1 of ‘pthread_join’ makes integer from pointer without a cast)
其中传递指向pthread_t
而不是pthread_t
的指针。
警告
cast to pointer from integer of different size
来自(void*) y
-如果您正在为64位目标进行编译,则int
比void*
更小。
你应该使用&y
或者给y
一个和void*
一样大的类型,比如int64_t
。
在runner
中,您将参数强制转换为int*
,这非常奇怪,因为它开始时是一个int
。
您需要确保将类型转换回开始时的相同类型。
然后使用这个值初始化一个int
,但这不可能是您的实际代码,因为以下错误与
int* y = (int *) param;
因此,我怀疑您在输入问题中的代码时丢失了一个"*“。
如果在参数中传递指向int
的指针,则应为
int y = *(int*) param;
如果您传递一个重新解释为指针的整数,它应该是
int64_t y = (int64_t) param;
如果你选择int64_t
作为你的整型。
此外,请记住,在线程修改数组元素时打印它们可能不是最好的想法,也不能确保线程不会超出数组边界。
发布于 2015-06-27 05:42:43
pthread_create(&tid, NULL, runner,(void *)y);
==>
for( i = 0; i < 3; i++){
pthread_create(&tid[i], NULL, runner,(void *)y);
}
和
pthread_join(tid, NULL);
==>
for( i = 0; i < 3; i++){
pthread_join(tid[i], NULL);
}
https://stackoverflow.com/questions/31082559
复制相似问题