C - pthread returns 意外结果
C - pthread returns unexpected result
我正试图弄清 C 中 pthreads 问题的根源。虽然我的第二个线程 returns 值正确,但第一个只给了我(我假设)一个内存地址。
代码应执行以下操作:
创建 2 个线程,从控制台计算给定数字的阶乘和指数值。
阶乘被编码为函数,指数计算器在主代码中。
感谢您的帮助!
#include <pthread.h>
#include <stdio.h>
void *fac_x(void *x_void_ptr)
{
int *x_ptr = (int *)x_void_ptr;
int counter = *x_ptr;
for (int i = 1; i < counter ; i++) {
*x_ptr *= i;
}
printf("x factorising finished\n");
return NULL;
}
int main()
{
int x,y, counter;
printf("Enter an integer: ");
scanf("%d",&x);
y = x;
counter = y;
printf("Input = %d\n",x);
pthread_t fac_x_thread;
if(pthread_create(&fac_x_thread, NULL, fac_x, &x)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
while (counter != 0) {
y *= y;
counter--;
}
if(pthread_join(fac_x_thread, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
printf("Factorial: %d \nExponential: %d\n", x, y);
return 0;
}
the first one just gives me (I assume) a memory address.
这不是地址,您(尝试)计算一个非常大的值,您很快就会溢出
对于 3,它已经是 6561(3*3 = 9、9*9 = 81,最后是 81*81=6561)
对于 4,32 位的值是 2^32(4*4=16、16*16=256、256*256=65536,最后是 65536*65536=4294967296=2^32)
对于 5,值为 23283064365386962890625 = 0x4EE2D6D415B85ACEF81 > 2^75 对于 64b 来说太大了!
我正试图弄清 C 中 pthreads 问题的根源。虽然我的第二个线程 returns 值正确,但第一个只给了我(我假设)一个内存地址。
代码应执行以下操作:
创建 2 个线程,从控制台计算给定数字的阶乘和指数值。
阶乘被编码为函数,指数计算器在主代码中。
感谢您的帮助!
#include <pthread.h>
#include <stdio.h>
void *fac_x(void *x_void_ptr)
{
int *x_ptr = (int *)x_void_ptr;
int counter = *x_ptr;
for (int i = 1; i < counter ; i++) {
*x_ptr *= i;
}
printf("x factorising finished\n");
return NULL;
}
int main()
{
int x,y, counter;
printf("Enter an integer: ");
scanf("%d",&x);
y = x;
counter = y;
printf("Input = %d\n",x);
pthread_t fac_x_thread;
if(pthread_create(&fac_x_thread, NULL, fac_x, &x)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
while (counter != 0) {
y *= y;
counter--;
}
if(pthread_join(fac_x_thread, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
printf("Factorial: %d \nExponential: %d\n", x, y);
return 0;
}
the first one just gives me (I assume) a memory address.
这不是地址,您(尝试)计算一个非常大的值,您很快就会溢出
对于 3,它已经是 6561(3*3 = 9、9*9 = 81,最后是 81*81=6561)
对于 4,32 位的值是 2^32(4*4=16、16*16=256、256*256=65536,最后是 65536*65536=4294967296=2^32)
对于 5,值为 23283064365386962890625 = 0x4EE2D6D415B85ACEF81 > 2^75 对于 64b 来说太大了!