C++:Linux平台上的线程同步场景

标签 c++ linux multithreading synchronization

我正在为 Linux 平台实现多线程 C++ 程序,我需要一个类似于 WaitForMultipleObjects() 的功能。

在寻找解决方案时,我发现有一些文章描述了如何在 Linux 中通过示例实现 WaitForMultipleObjects() 功能,但这些示例不满足我必须支持的场景。

我的情况非常简单。我有一个守护进程,其中主线程向外界公开一个方法/回调,例如一个 DLL。 DLL 的代码不在我的控制之下。同一个主线程创建了一个新线程“Thread 1”。线程 1 必须执行某种无限循环,在该循环中它将等待关闭事件(守护程序关闭),或者它会等待通过上述公开的方法/回调发出信号的数据可用事件。

简而言之,线程将等待关闭事件和数据可用事件,如果关闭事件发出信号,等待将满足并且循环将被中断,或者如果数据可用事件发出信号,则等待也将满足并且线程将执行业务处理。

在 Windows 中,它看起来非常简单。下面是我的场景的基于 MS Windows 的伪代码。

//**Main thread**

//Load the DLL
LoadLibrary("some DLL")

//Create a new thread
hThread1 = __beginthreadex(..., &ThreadProc, ...)

//callback in main thread (mentioned in above description) which would be called by the     DLL
void Callbackfunc(data)
{
    qdata.push(data);
    SetEvent(s_hDataAvailableEvent);
}

void OnShutdown()
{
    SetEvent(g_hShutdownEvent);
    WaitforSingleObject(hThread1,..., INFINITE);
    //Cleanup here
}

//**Thread 1**

unsigned int WINAPI ThreadProc(void *pObject)
{
    while (true)
    {

        HANDLE hEvents[2];
        hEvents[0] = g_hShutdownEvent;
        hEvents[1] = s_hDataAvailableEvent;

        //3rd parameter is set to FALSE that means the wait should satisfy if state of  any one of the objects is signaled.
        dwEvent = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
        switch (dwEvent) 
        {   
            case WAIT_OBJECT_0 + 0: 
            // Shutdown event is set, break the loop
            return 0;   

            case WAIT_OBJECT_0 + 1:
            //do business processing here
            break; 

            default: 
            // error handling
        }
    }
}

我想为 Linux 实现相同的功能。根据我对 Linux 的理解,它具有完全不同的机制,我们需要在其中注册信号。如果终止信号到达,进程将知道它即将关闭,但在此之前,进程有必要等待正在运行的线程正常关闭。

最佳答案

在 Linux 中执行此操作的正确方法是使用条件变量。虽然这与 Windows 中的 WaitForMultipleObjects 不同,但您将获得相同的功能。

使用两个 bool 来确定是否有可用数据或是否必须关闭。 然后让关闭函数和数据函数都相应地设置 bool 值,并向条件变量发出信号。

#include <pthread.h>

pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_t hThread1; // this isn't a good name for it in linux, you'd be 
                    // better with something line "tid1" but for 
                    // comparison's sake, I've kept this

bool shutdown_signalled;
bool data_available;

void OnShutdown()
{
    //...shutdown behavior...
    pthread_mutex_lock(&mutex);
    shutdown_signalled = true;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cv);
}

void Callbackfunc(...)
{
    // ... whatever needs to be done ...
    pthread_mutex_lock(&mutex);
    data_available = true;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cv);
}


void *ThreadProc(void *args)
{
    while(true){
        pthread_mutex_lock(&mutex);
        while (!(shutdown_signalled || data_available)){
            // wait as long as there is no data available and a shutdown
            // has not beeen signalled
            pthread_cond_wait(&cv, &mutex);
        }
        if (data_available){
            //process data
            data_available = false;
        }
        if (shutdown_signalled){
            //do the shutdown
            pthread_mutex_unlock(&mutex);
            return NULL;
        }
        pthread_mutex_unlock(&mutex); //you might be able to put the unlock
        // before the ifs, idk the particulars of your code
    }
}
int main(void)
{
    shutdown_signalled = false;
    data_available = false;
    pthread_create(&hThread1, &ThreadProc, ...);
    pthread_join(hThread1, NULL);
    //...
}

我知道 Windows 也有条件变量,所以这看起来应该不会太陌生。我不知道 Windows 对它们有什么规定,但在 POSIX 平台上,wait 需要在 while 循环内,因为可能会发生“虚假唤醒”。

关于C++:Linux平台上的线程同步场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16038877/

相关文章:

java - 为什么当通过 JNI 在 Java 代码中运行 EGL 函数时,我对 EGL 函数的调用会发生变化?

linux - 从线程 ID 获取 pthread_t

c# - 使用 ADO.Net 多线程访问 MySQL

java - 我不懂线程

linux - 无法连接到多线程 CURL 中的主机(错误 7)mipsel-linux mipsel 多核架构师

c++ - 错误 : no match for 'operator*' (operand types are 'std: :string {aka std basic_string<char>}' and {aka std basic_string<char>}')

c++ - 使用 boost::future 和 "then"延续

c++ - file.get() 在 C++ 循环后返回随机数

linux - 如何拦截 Linux 桌面上的 HTTP 请求?

linux - 如何获取行号?