警告:格式'%d'需要类型为'int'的参数,但参数2的类型为'long int'[-Wformat =]

Zey*_*eel 6 c unix multithreading thread-synchronization

这段代码是关于.

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

我是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);
Run Code Online (Sandbox Code Playgroud)

这是代码:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Iha*_*imi 11

你必须改变"%d""%ld","%d"对已签名的int,这里的l代表long,以便"%ld"对已签名long int.