#include <iostream>
#include <process.h>
using namespace std;short g;void newthread(void* IntN);int main(){
    short IntN = 0;
    _beginthread( newthread, 0, (void*)IntN );
    system( "pause" );
    cout<<g<<endl;
    return 1;
}void newthread(void* IntN)
{
    short x = (short) IntN;
    x ++;
    g = x;
    cout << "fuck" << endl;
    cout << g;
    _endthread();
}若将以上代码改成:
#include <iostream>
#include <process.h>
using namespace std;short g;void newthread(void* IntN);int main(){
    short IntN = 0;
    _beginthread( newthread, 0, (void*)IntN );
    cout<<g<<endl;
    system( "pause" );
    return 1;
}void newthread(void* IntN)
{
    short x = (short) IntN;
    x ++;
    g = x;
    cout << "fuck" << endl;
    cout << g;
    _endthread();
}
输出结果就会变掉, 如果不加system("pause")的话, 创建新线程的函数似乎根本就不执行, 直接输出g的值为0, 这是为什么啊??????

解决方案 »

  1.   

    不是吧, 第一段的程序总是输出fuck 1 1
    第二段总是输出0 fuck 1
    如果把system("pause")去掉的话就直接输出0了, 每次都这样的啊...请教下,如果要加同步应该怎么加?
      

  2.   

    如果中间不加停留,还不等子线程做完事,主线程就return了,自然整个进程就退掉了。
      

  3.   

    可以试着在主线程当中使用WaitFor*等子线程处理完再继续往下走。
      

  4.   


    那又怎么样,你挂起主线程或者WaitFor看看。(SuspendThread(GetCurrentThread()),挂起。或者,CreatSemaphore,然后主线程等待这个Semaphore,让你新建的线程发出信号激活他)线程就是脱缰的野马,如果没有同步控制,是不会像你想的那样运行的,若是那样,也只是碰巧。
      

  5.   

    搞定, 改成#include <iostream>
    #include <process.h>
    using namespace std;short g;
    bool tag = true;void newthread(void* IntN);int main(){
        short IntN = 0;
        _beginthread( newthread, 0, (void*)IntN );
        while(tag)
            continue;
        cout<<g<<endl;
        return 1;
    }void newthread(void* IntN)
    {
        short x = (short) IntN;
        x ++;
        g = x;
        cout << "fuck" << endl;
        cout << g << endl;
        tag = false;
        _endthread();
    }
    就可以了, 谢谢大家了