c++ - 设计线程类

标签 c++ windows multithreading mutex c++builder

我有一个设计问题。为发送和接收定义单独的类是否更好。或者,定义单个 Thread 类是否更好?我喜欢单个 Thread 类的想法,因为它更容易共享可以被互斥锁锁定的队列。

设计选项#1(独立):

mySendThread = new SendThread(); // Have thread properties and separate members

myRcvThread = new RcvThread(); // Have thread properties and separate members

设计选项 #2(主):

主线程-

Execute() 
{
    if (threadType == RCV_THREAD)
    {
        globalVar = new MasterThread(serialPortHandle);
    }
    while (!Terminated)
    {
        if (threadType == RCV_THREAD)
        {
            if(globalVar) 
            {  
                // do work
            }
        }
        if (threadType == SND_THREAD)
        {
            tCountSnd = GetTickCount() / SND_THREAD_DELAY;
            if (tCountSnd != tCountSnd2) {
               tCountSnd2 = tCountSnd;
               if (globalVar) {
                   // do sending work
               }
            }
        }
     }
}

最佳答案

我认为最好将线程的目的或执行与您将使用的实际线程抽象完全分离。

让您的线程类只是一个薄包装器,以允许您启动、停止和加入线程。让它在构造函数中获取一个仿函数对象(或函数指针)以进行实际执行。

或者更好的是,使用现有的许多可用线程抽象之一,而不是编写自己的线程抽象(例如 boost::thread,但我敢打赌您使用的任何框架都已经有一个线程类)。

关于c++ - 设计线程类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2096084/

相关文章:

c - 在 C 中使用 EOF 和 getchar() 进行字符计数

c++ - 如何编写可以在 Linux 和 Windows 中轻松编译的 C++ 程序?

python - Pygame帮助2.7

multithreading - 操作系统中的轻量级线程

c++ - Qt 如何在连接到其 clicked() 信号的插槽运行时使按钮响应?

c++ - 如何正确定义析构函数

c++ - boost::interprocess 共享内存 - 仅在一个应用程序中无法读取

C++ 从非右值对象访问右值引用对象

java - SwingWorker 中的进度对话框

c++ - Visual Studio 2015 git 推送到网络驱动器