gpt4 book ai didi

c - 使用线程打印全局变量

转载 作者:行者123 更新时间:2023-12-03 12:52:02 25 4
gpt4 key购买 nike

这是我的代码,我在CodeBlocks上编写脚本,但在Cygwin上进行编译。当我执行代码时,最终的printf向我显示0,而我不明白为什么。我尝试了我所知道的一切。我在读高中四年级。此代码接受一个int变量(sec),并用它来计算胶片的重量。

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

long long int layer=1;

void* res_VGA (void* sec){
int tempo = (intptr_t) sec;
int res = 640*480; //resolution
int frame = res * 3; // the rgb
long long int layer = frame * 25; // 25 frame Hz
layer * tempo;
layer/1000000000; // I need this for getting the gigabyte
pthread_exit(0);
}
void* res_HD (void* sec){
int tempo = (intptr_t) sec;
int res = 1080*720;
int frame = res * 3;
long long int layer = frame * 25;
layer * tempo;
layer/1000000000;
pthread_exit(0);
}
void* res_FHD (void* sec){
int tempo = (intptr_t) sec;
int res = 1920*1080;
int frame = res * 3;
long long int layer = frame * 25;
layer * tempo;
layer/1000000000;
pthread_exit(0);
}
int main(){
int sec,res;
pthread_t t1;
printf("Inserisci il numero di secondi: \n");
scanf("%d",&sec);
printf("Seleziona il tipo di risoluzione: \n");
printf("1) VGA \n");
printf("2) HD \n");
printf("3) FHD \n");
do{
scanf("%d",&res);
if(res == 1){
pthread_create(&t1, NULL, res_VGA, (void*)(intptr_t)sec);
}
else if(res == 2){
pthread_create(&t1, NULL, res_HD, (void*)(intptr_t)sec);
}
else if(res == 3){
pthread_create(&t1, NULL, res_FHD, (void*)(intptr_t)sec);
}
}while(res != 1 && res != 2 && res != 3);
printf("Il film pesa %lld byte", layer/1000000000);

return 0;
}

最佳答案

您有多个问题。

1)在这里

  layer * tempo;
layer/1000000000; // I need this for getting the gigabyte

您是计算层,但丢弃结果!

您可能想要:
  layer = layer * tempo;
layer = layer/1000000000;

需要对所有线程进行此更改。

2) layerlong long。因此,最终的除法( layer = layer/1000000000)可能为零(由于整数除法)。而是使用 long double

3)您有一个局部变量 long long int layer;,它遮盖了全局变量。如果要存储结果(与本地计算值并返回结果相反),请更改:
long long int  layer = frame * 25;


layer = frame * 25;

需要对所有线程功能进行此更改。

4)您 main()线程不等待其他线程完成。因此它可能在其他线程完成之前退出。因此,创建线程后,您应该在 pthread_exit(0)中调用 pthread_join(t1, 0);main()

main()退出时,整个过程终止。 pthread_join()将使其等待线程完成。 pthread_exit()将确保仅主线程死亡,而不是整个过程终止。

关于c - 使用线程打印全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34262070/

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