我写了这段代码
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
unsigned int cnt=0; /*Count variable%*/
const int NITERS=1000;
void count()
{
int i=0;
for(i=0; i<NITERS; i++)
{
cnt++;
}
pthread_exit(0);
}
int main()
{
pthread_t tid1,tid2;
/* create threads 1 and 2 */
pthread_create(&tid1,NULL,count,NULL);
pthread_create(&tid2,NULL,count,NULL);
/* Main block now waits for both threads to terminate, before it exits
If main block exits, both threads exit, even if the threads have not
finished their work */
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
if(cnt!=(unsigned)NITERS*2)
{
printf("BOOM! cnt=%d, it should be %d\n",cnt,NITERS*2);
}
else
{
printf("OK! cnt=%d\n",cnt);
}
exit(0);
}
它展示了这个结果。
有时它的 cnt 为 2000,但大多数时候它给出的结果小于 2000。你能解释一下为什么会发生这种情况或这背后的原因是什么?如何修复它。你的回答和理由肯定会大有帮助。