以下是一个使用MFC实现的多线程运行的示例代码:

#include <afxwin.h>
#include <afxmt.h>
#include <iostream>

using namespace std;

class CMyThread : public CWinThread
{
public:
    CMyThread() {}

    BOOL InitInstance()
    {
        // 进行线程初始化操作
        cout << "Thread " << GetCurrentThreadId() << " is running." << endl;
        return TRUE;
    }

    int ExitInstance()
    {
        // 进行线程退出操作
        cout << "Thread " << GetCurrentThreadId() << " has exited." << endl;
        return CWinThread::ExitInstance();
    }
};

class CMyApp : public CWinApp
{
public:
    CMyApp() {}

    BOOL InitInstance()
    {
        // 创建多个线程
        CMyThread* thread1 = new CMyThread();
        CMyThread* thread2 = new CMyThread();

        // 启动线程
        thread1->CreateThread();
        thread2->CreateThread();

        // 判断是否有线程在运行
        while (thread1->m_bAutoDelete || thread2->m_bAutoDelete)
        {
            Sleep(1000); // 暂停1秒钟
        }

        // 所有线程都安全退出
        cout << "All threads have safely exited." << endl;

        return CWinApp::InitInstance();
    }
};

CMyApp theApp;

在上面的代码中,我们创建了两个线程并启动它们。然后,我们使用一个循环来判断是否有线程在运行。如果线程的m_bAutoDelete标志为真,表示线程已经退出,我们就可以安全地退出整个进程。

请注意,这种方式并不是一个好的线程同步方法,因为它依赖于线程的退出标志,并且没有使用互斥锁来保护共享资源。在实际的多线程编程中,我们应该使用互斥锁或其他线程同步机制来确保线程安全。这只是一个简单的示例代码,仅用于演示目的

mfc代码实现模拟多个线程运行不加互斥锁判断该进程中是否有线程在运行在运行的线程安全退出

原文地址: https://www.cveoy.top/t/topic/iWAH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录