xiaolongrenstep 2017-04-06 13:46 采纳率: 0%
浏览 1292

为什么只有Thread1一直在执行而Thread2 没有呢?

本人新手小白,在学习互斥对象这部分内容时编写的程序如下,为什么只有Thread1一直在执行而Thread2 没有呢?
#include "stdafx.h"
#include
#include
#include

using namespace std;
//using std::cout;
int tickets = 100;
HANDLE hMutex;

DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while (true)
{
WaitForSingleObject(hMutex,INFINITE);

if (tickets>0)
{
    Sleep(1);
    cout <<"Thread1 sell "<< tickets-- << endl;
}
ReleaseMutex(hMutex);

}
//cout << "Thread1 is running\n"<< endl;
return 0;

}

DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
while (true)
{
WaitForSingleObject(hMutex, INFINITE);
if (tickets>0)
{
Sleep(1);
cout <<"Thread2 sell "<< tickets-- << "\n" << endl;
}
ReleaseMutex(hMutex);
return 0;
}

}

void main()
{
HANDLE hThread1;
HANDLE hThread2;

hThread1 = CreateThread(
    NULL, // SD
    0,                        // initial stack size
    Fun1Proc,    // thread function
    0,                       // thread argument
    0,                    // creation option
    NULL                        // thread identifier
    );
CloseHandle(hThread1);

hThread2 = CreateThread(NULL,0,Fun2Proc,0,0,NULL);
CloseHandle(hThread1);
//char c[] = "tickets";
hMutex =CreateMutex(NULL,FALSE,"sasdasdfasdfa");
//WaitForSingleObject(hMutex, INFINITE);
//hMutex = CreateMutex(NULL, TRUE, "tickets");
//ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);

system("pause");

}

  • 写回答

1条回答 默认 最新

  • merlin’s girl 2017-04-06 14:56
    关注

    hThread1 = CreateThread(
    NULL, // SD
    0, // initial stack size
    Fun1Proc, // thread function
    0, // thread argument
    0, // creation option
    NULL // thread identifier
    );
    CloseHandle(hThread1);

    hThread2 = CreateThread(NULL,0,Fun2Proc,0,0,NULL);
    CloseHandle(hThread1);//这里为什么还是hThread1??????????????

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度