简体   繁体   English

如何使用 pthreads 通知线程新数据可用?

[英]How do I notify a thread that new data is available using pthreads?

I have new data appearing over a bus.我有新数据出现在公共汽车上。 I want my main thread to "wake up" when the new data arrives.我希望我的主线程在新数据到达时“醒来”。 My original version of the code is this:我的原始代码版本是这样的:

#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

int data = 0;

void* thread_func(void* args)
{
    while(1)
    {
        sleep(2);
        
        data = random() % 5;
    }
    
    return NULL;
}


int main()
{
    int tid;

    pthread_create(&tid, NULL, &thread_func, NULL);
    
    while(1)
    {
        // Check data.
        printf("New data arrived: %d.\n", data);
        sleep(2);
    }
    
    return 0;
}

But clearly an infinite while loop in the main thread is overkill.但显然主线程中的无限 while 循环是多余的。 So I thought how about this?所以我想这个怎么样?

#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

int data = 0;
pthread_mutex_t mtx;

void* thread_func(void* args)
{
    while(1)
    {
        sleep(2);
        
        // Data has appeared and can be read by main().
        data = random() % 5;
        
        pthread_mutex_unlock(&mtx);
    }
    
    return NULL;
}


int main()
{
    int tid;
       

    pthread_mutex_init(&mtx, NULL);
    
    pthread_create(&tid, NULL, &thread_func, NULL);
    
    while(1)
    {
        pthread_mutex_lock(&mtx);
        printf("New data has arrived: %d.\n", data);
    }
    
    return 0;
}

This works, but is it the best way?这可行,但这是最好的方法吗?

In actual fact, I don't just have a main thread, but several threads that I would like to be asleep until new data for them arrived.事实上,我不仅有一个主线程,还有几个线程,我希望它们处于睡眠状态,直到它们的新数据到达为止。 This would involve using one mutex lock for each thread.这将涉及为每个线程使用一个互斥锁。 Is this the best way to do things?这是最好的做事方式吗?

I hope it's clear.我希望这很清楚。 Thanks.谢谢。

You can use pthread_cond_wait to wait for a change on the data you share between your threads.您可以使用pthread_cond_wait来等待您在线程之间共享的数据发生变化。 This function automatically blocks your mutex and you have to release it afterwards.这个 function 会自动阻止你的互斥体,你必须在之后释放它。 To notify your threads that the data is ready use the pthread_cond_signal function.要通知您的线程数据已准备就绪,请使用pthread_cond_signal function。

But be careful, you must always lock and unlock your mutex in each of your threads, not as you do in your example.但是要小心,您必须始终在每个线程中锁定和解锁互斥量,而不是像您的示例中那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM