Условия проведения соревнований: Планирование и поведение компилятора играют важную роль в синхронизации процессов или потоков. Самый простой сценарий, демонстрирующий необходимость синхронизации, исходит из условий гонки, созданных между двумя потоками/процессом, пытающимися изменить значение общей переменной, что обычно приводит к несогласованности данных и ошибочным результатам. Следующий пример демонстрирует эту ситуацию:
Я новичок в 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;
}
Правильный отступ сделает ваш код * намного * более легким для чтения. –
Обратите внимание, что copy'n'paste приводит к тому, что вы создаете (или не создаете) «поток 1» три раза и присоединяете (или не присоединяетесь) «поток 1» четыре раза. Помимо необходимости использовать массивы, вы также должны помнить, что полностью отредактируйте код при его повторном копировании. –