多线程输出乱码,帮忙看看,谢谢咯!
最近在学习多线程,同样的代码,每次输出的方式和结果都不一样,不知道哪里出问题,麻烦大虾帮忙看看。代码如下:
程序代码:
#include "stdafx.h" #include <Windows.h> #include <iostream> using namespace std; DWORD WINAPI Func_thread1(LPVOID lpparameter); DWORD WINAPI Func_thread2(LPVOID lpparameter); HANDLE tar_event; int tickets = 100; void main() { HANDLE tar_thread1; tar_thread1 = CreateThread(NULL,0,Func_thread1,NULL,0,NULL); CloseHandle(tar_thread1); HANDLE tar_thread2; tar_thread2 = CreateThread(NULL,0,Func_thread2,NULL,0,NULL); CloseHandle(tar_thread2); tar_event = CreateEvent(NULL, FALSE,FALSE,NULL); //自动重置事件,初始无信号; SetEvent(tar_event); CloseHandle(tar_event); Sleep(800); } DWORD WINAPI Func_thread1(LPVOID lpparameter) { while(TRUE) { WaitForSingleObject(tar_event,INFINITE); if (tickets >0) { Sleep(1); cout<<"thread 1 sell ticket :"<<tickets--<< endl; // printf("thread 1 sell ticket :%d \n",tickets--); SetEvent(tar_event); } else { SetEvent(tar_event); break; } // SetEvent(tar_event); } return 0; } DWORD WINAPI Func_thread2(LPVOID lpparameter) { while(TRUE) { WaitForSingleObject(tar_event,INFINITE); if (tickets >0) { Sleep(1); cout<<"thread 2 sell ticket :"<<tickets--<<endl; // printf("thread 2 sell ticket :%d \n",tickets--); SetEvent(tar_event); } else { SetEvent(tar_event); break; // SetEvent(tar_event); } return 0; } }[local]1[/local][local]2[/local][local]3[/local]
输出结果每次都不一样。不知道是为什么。