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

C 如何使用pthreads通知线程新数据可用?,c,linux,multithreading,mutex,C,Linux,Multithreading,Mutex,我有新的数据出现在总线上。我希望我的主线程在新数据到达时“唤醒”。我的原始代码版本如下: #include <time.h> #include <stdio.h> #include <pthread.h> #include <time.h> int data = 0; void* thread_func(void* args) { while(1) { sleep(2); dat

我有新的数据出现在总线上。我希望我的主线程在新数据到达时“唤醒”。我的原始代码版本如下:

#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;
}
#包括
#包括
#包括
#包括
int数据=0;
void*thread\u func(void*args)
{
而(1)
{
睡眠(2);
数据=随机()%5;
}
返回NULL;
}
int main()
{
国际贸易署;
pthread_create(&tid,NULL,&thread_func,NULL);
而(1)
{
//检查数据。
printf(“新数据到达:%d.\n”,数据);
睡眠(2);
}
返回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;
}
#包括
#包括
#包括
#包括
int数据=0;
pthread_mutex_t mtx;
void*thread\u func(void*args)
{
而(1)
{
睡眠(2);
//数据已出现,可由main()读取。
数据=随机()%5;
pthread_mutex_unlock(&mtx);
}
返回NULL;
}
int main()
{
国际贸易署;
pthread_mutex_init(&mtx,NULL);
pthread_create(&tid,NULL,&thread_func,NULL);
而(1)
{
pthread_mutex_lock(&mtx);
printf(“新数据已到达:%d.\n”,数据);
}
返回0;
}
这是可行的,但这是最好的方法吗

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

我希望这是清楚的。谢谢。

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


<>但是要小心,你必须始终锁定和解锁你的互斥锁在你的每一个线程,而不是像你在你的例子中。< /P> C++或C++?这些是完全不同的语言。这看起来像是100% C代码。语言不可知的关键字是消息队列。查找“信号量”。嗨,我写了C代码简单,并且宁愿坚持,除非C++提供有用的工具。你锁定一个线程,但是在另一个线程中解锁……并且注意你的条件变量的“杂散唤醒”现象。要了解更多信息,请单击。谢谢,这似乎符合我的要求。