【问题标题】:How do I notify a thread that new data is available using pthreads?如何使用 pthreads 通知线程有新数据可用?
【发布时间】:2021-07-07 10:20:57
【问题描述】:

我有新数据出现在公共汽车上。我希望我的主线程在新数据到达时“唤醒”。我原来的代码是这样的:

#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;
}

但显然主线程中的无限 while 循环是多余的。所以我想这个怎么样?

#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;
}

这可行,但这是最好的方法吗?

实际上,我不仅有一个主线程,还有几个线程,我希望它们处于休眠状态,直到它们的新数据到达。这将涉及为每个线程使用一个互斥锁。这是最好的做事方式吗?

我希望它很清楚。谢谢。

【问题讨论】:

  • C C++?这些是完全不同的语言。这看起来像是 100% 的 C 代码。
  • 与语言无关的关键字是 message queue
  • 查找“信号量”。
  • 嗨,为了简单起见,我编写了 C 代码,除非 C++ 提供有用的工具,否则我宁愿坚持下去。
  • 你锁定一个线程,但解锁另一个线程?...

标签: c linux multithreading mutex


【解决方案1】:

您可以使用pthread_cond_wait 等待线程之间共享的数据发生更改。此功能会自动阻止您的互斥锁,您必须在之后释放它。要通知您的线程数据已准备就绪,请使用 pthread_cond_signal 函数。

但请注意,您必须始终在每个线程中锁定和解锁互斥锁,而不是像您在示例中那样。

【讨论】:

  • 并提防条件变量的“虚假唤醒”现象。要了解更多信息,请点击here
  • 谢谢,这似乎是我想要的。
猜你喜欢
  • 2011-10-20
  • 2023-04-10
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 2013-01-06
  • 1970-01-01
相关资源
最近更新 更多