创建两个线程,分别输出信息。
但是信息刚输出一半或部分,线程就发生切换
转而输出另部分内容,造成信息混乱。请问如何解决?如:示例效果是这样的Thread1 sell ticket: 100
Thread2 sell ticket: 100
Thread2 sell ticket: 100
Thread1 sell ticket: 100
.......
.......
实际效果
Thread1 sell ticThread2 sell ticket:99
Thread2 sket:100
Thread1 sell ticket:97
Threell ticket:98
Thread2 sell ticket:9ad1 sell ticket:96#include<windows.h>
#include<iostream>DWORD WINAPI Fun1Proc(LPVOID  lp);
DWORD WINAPI Fun2Proc(LPVOID  lp);
using namespace std;int tickets = 100;int main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(4000);
return 0;
}
DWORD WINAPI Fun1Proc(LPVOID  lp)
{
while(true)
{
if(tickets>0)
{
cout<<"Thread1 sell ticket:"<<tickets--<<endl;
}
else
break;
} return 0;
}DWORD WINAPI Fun2Proc(LPVOID  lp)
{ while(true)
{
if(tickets>0)
{
cout<<"Thread2 sell ticket:"<<tickets--<<endl;
}
else
break;
}
return 0;
}

解决方案 »

  1.   

    先改用_beginthreadex创建线程 试试。
      

  2.   

    本身进程就是抢占资源输出的,楼主要控制的话,可以用信号互斥Mutex或者Event
      

  3.   

    线程加锁#include <windows.h>
    #include <iostream.h>DWORD WINAPI Fun1Proc(
      LPVOID lpParameter   // thread data
    );DWORD WINAPI Fun2Proc(
      LPVOID lpParameter   // thread data
    );
    int index=0;
    int tickets=100;
    HANDLE hMutex;
    void main()
    {
    HANDLE hThread1;
    HANDLE hThread2;
    hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
    hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
    CloseHandle(hThread1);
    CloseHandle(hThread2);

    hMutex=CreateMutex(NULL,TRUE,"tickets");
    if(hMutex)
    {
    if(ERROR_ALREADY_EXISTS==GetLastError())
    {
    cout<<"only instance can run!"<<endl;
    return;
    }
    }
    WaitForSingleObject(hMutex,INFINITE);
    ReleaseMutex(hMutex);
    ReleaseMutex(hMutex);
    Sleep(4000);}DWORD WINAPI Fun1Proc(
      LPVOID lpParameter   // thread data
    )
    {
    while(TRUE)
    {
    WaitForSingleObject(hMutex,INFINITE);
    if(tickets>0)
    {
    Sleep(1);
    cout<<"thread1 sell ticket : "<<tickets--<<endl;
    }
    else
    break;
    ReleaseMutex(hMutex);
    } WaitForSingleObject(hMutex,INFINITE);
    cout<<"thread1 is running"<<endl;
    return 0;
    }DWORD WINAPI Fun2Proc(
      LPVOID lpParameter   // thread data
    )
    {

    while(TRUE)
    {
    //ReleaseMutex(hMutex);
    WaitForSingleObject(hMutex,INFINITE);
    if(tickets>0)
    {
    Sleep(1);
    cout<<"thread2 sell ticket : "<<tickets--<<endl;
    }
    else
    break;
    ReleaseMutex(hMutex);
    }
    WaitForSingleObject(hMutex,INFINITE);
    cout<<"thread2 is running"<<endl;
    return 0;
    }