【发布时间】:2011-06-22 04:46:30
【问题描述】:
好的,我有一个关于线程的问题。
有两个不同步的线程同时运行并使用全局资源“int num” 第一个:
void Thread()
{
int i;
for ( i=0 ; i < 100000000; i++ )
{
num++;
num--;
}
}
第二个:
void Thread2()
{
int j;
for ( j=0 ; j < 100000000; j++ )
{
num++;
num--;
}
}
问题说明:程序末尾的变量“num”的可能值是多少。 现在我会说 0 将是程序末尾的 num 的值,但是,尝试运行这段代码,你会发现结果是非常随机的, 我不明白为什么?
完整代码:
#include <windows.h>
#include <process.h>
#include <stdio.h>
int static num=0;
void Thread()
{
int i;
for ( i=0 ; i < 100000000; i++ )
{
num++;
num--;
}
}
void Thread2()
{
int j;
for ( j=0 ; j < 100000000; j++ )
{
num++;
num--;
}
}
int main()
{
long handle,handle2,code,code2;
handle=_beginthread( Thread, 0, NULL );
handle2=_beginthread( Thread2, 0, NULL );
while( (GetExitCodeThread(handle,&code)||GetExitCodeThread(handle2,&code2))!=0 );
TerminateThread(handle, code );
TerminateThread(handle2, code2 );
printf("%d ",num);
system("pause");
}
【问题讨论】:
-
@Marlon:不正确。请参阅@Thomas 的回答。
标签: c++ c multithreading thread-safety