【发布时间】:2015-02-27 19:16:56
【问题描述】:
这段代码是关于。
比赛条件: 调度和编译器行为在进程或线程同步中起着重要作用。演示同步需求的最简单场景来自试图修改共享变量值的两个线程/进程之间创建的竞争条件,这通常会导致数据不一致和错误结果。下面的例子演示了这种情况:
我是 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”四次。除了需要使用数组之外,您还需要记住在复制代码时对其进行完全编辑。
标签: c multithreading unix thread-synchronization