C:Linux平台上的线程同步方案

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

在搜索解决方案时,我观察到有些文章描述了如何在Linux中使用示例实现WaitForMultipleObjects()功能,但这些示例不满足我必须支持的场景.

我的情况非常简单.我有一个守护进程,主线程将一个方法/回调暴露给外部世界,例如暴露给DLL. DLL的代码不在我的控制之下.相同的主线程创建一个新线程“线程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平台上,等待需要在while循环中,因为“虚假的唤醒”可能会发生.

上一篇:linux – 这个规范的群集示例如何工作?


下一篇:javascript – 如何使表单提交同步?