gpt4 book ai didi

c - 警告 : format ‘%d’ expects argument of type ‘int’ , 但参数 2 的类型为 ‘long int’ [-Wformat=]

转载 作者:太空狗 更新时间:2023-10-29 17:19:09 27 4
gpt4 key购买 nike

这段代码是关于。

比赛条件:调度和编译器行为在进程或线程同步中起着重要作用。证明需要同步的最简单场景来自试图修改共享变量值的两个线程/进程之间创建的竞争条件,这通常会导致数据不一致和错误结果。以下示例演示了这种情况:

我是 C 的新手,我对这个警告所发生的事情有疑问。警告是什么意思,我该如何解决。我写的代码在这里:

q1.c: In function ‘runner’:
q1.c:13:1: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf("T tid: %d x before: %d\n", syscall(SYS_gettid),x); int i;
^
q1.c:19:1: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf("T tid: %d x after: %d\n", syscall(SYS_gettid),x);

代码如下:

// Race condition
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
int x=0;
void * runner(void *arg)
{
printf("T tid: %d x before: %d\n", syscall(SYS_gettid),x); int i;
for (i = 0; i < 100000; i++ )
{
x = x + 1;
}
printf("T tid: %d x after: %d\n", syscall(SYS_gettid),x);
}

int program()
{
pthread_t t1,t2,t3,t4;
printf("Parent pid: %d x before threads: %d\n", getpid(),x); int i;
if(pthread_create(&t1,NULL, runner, NULL)){ printf("Error creating thread 1\n"); return 1;
}
if(pthread_create(&t2,NULL, runner, NULL)){ printf("Error creating thread 2\n"); return 1;
}
if(pthread_create(&t3,NULL, runner, NULL)){ printf("Error creating thread 1\n"); return 1;
}
if(pthread_create(&t4,NULL, runner, NULL)){ printf("Error creating thread 1\n"); return 1;
}

if(pthread_join(t1,NULL)){ printf("error joining thread 1"); return 1;
}
if(pthread_join(t2,NULL)){ printf("error joining thread 1"); return 1;
}
if(pthread_join(t3,NULL)){ printf("error joining thread 1"); return 1;
}

if(pthread_join(t4,NULL)){ printf("error joining thread 1"); return 1;
}
printf("Parent pid: %d x after threads: %d\n", getpid(),x); return 0;
}

int main(int argc, char *argv[]) {
int count=0;
// loop runs the program count times
while(count<5)
{
// running program program();
count++;
//reset global x for next run of program. x=0;
printf("\n\n");
}
return 0;
}

最佳答案

您必须将 "%d" 更改为 "%ld""%d" 用于签名 int 而这里的 l 代表 long 所以 "%ld" 代表有符号的 long int

关于c - 警告 : format ‘%d’ expects argument of type ‘int’ , 但参数 2 的类型为 ‘long int’ [-Wformat=],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27725531/

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