#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
答案 0 :(得分:3)
无论出于何种原因,您都要声明一组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;
所以我怀疑你输了#34; *&#34;输入问题中的代码时。
如果您在参数中传递指向int
的指针,则应为
int y = *(int*) param;
如果传递一个重新解释为指针的整数,它应该是
int64_t y = (int64_t) param;
如果您确定int64_t
作为整数类型。
另外,请记住,在线程修改它们时打印数组元素可能不是最好的想法,也不能确保线程不会超出数组边界。
答案 1 :(得分:-1)
pthread_create(&tid, NULL, runner,(void *)y);
==&GT;
for( i = 0; i < 3; i++){
pthread_create(&tid[i], NULL, runner,(void *)y);
}
和
pthread_join(tid, NULL);
==&GT;
for( i = 0; i < 3; i++){
pthread_join(tid[i], NULL);
}