简体   繁体   English

pthread读/写同步

[英]pthread read/write synchronisation

This seems to be a simple task, but it doesnt work. 这似乎是一个简单的任务,但没有用。 My threadfunction runs in a loop and writes data into an array all the time. 我的线程函数循环运行,并始终将数据写入数组。 But sometimes I want to read this data from my main function. 但是有时候我想从我的主要功能中读取这些数据。 Therefore the read-funtion should ideally pause the thread, read the data, and then resume the thread. 因此,理想情况下,读取功能应暂停线程,读取数据,然后恢复线程。 But the value that is read is not correct and seems corrupted. 但是读取的值不正确,并且似乎已损坏。 Maybe there is something wrong: 也许有问题:

thread-fct: 线程FCT:

void threadfct()
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        data = write_data();
        pthread_mutex_unlock(&mutex);
    }
}

Function that is called from main-loop should read that data that is written by the thread-function: 从主循环调用的函数应读取由线程函数写入的数据:

void read_data()
{
    printf("Daten: %f\n", data[0]);
}

try this change: 尝试此更改:

void read_data()
{
    pthread_mutex_lock(&mutex);
    printf("Daten: %f\n", data[0]);
    pthread_mutex_unlock(&mutex);
}

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

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