我正在使用C中的pthread。我有线程1从一块硬件接收数据,并将该数据放入队列中。我有线程2,当数据在队列中并处理该数据时会得到通知。我的实际代码的伪代码如下。
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void* inputThread(void *ptr){
while(){
getData(var1); //Notified by external hardware interrupt when data is available. var1 will hold new data
enqueue(q1, var1);
pthread_mutex_lock(&lock1);
pthread_cond_signal(&condition1);
pthread_mutex_unlock(&lock1);
}
}
void* processDataThread(void *ptr){
short data_to_process[];
while(){
pthread_mutex_lock(&lock1);
while (emptyqueue(q1)) {
pthread_cond_wait(&condition1,&lock1); //wait for inputthread to fill queue
}
data_to_process=dequeue(q1);
pthread_mutex_unlock(&lock1);
process_data(data_to_process); //causes thread to slow down
}
}
int main(void){
pthread_t input_thread_id;
pthread_t thr[10];
struct queue q1;
struct queue q2;
//
//
//some code to initiate queues, locks/mutex, conditions, etc.
//
//
for (j) {
pthread_create(&thr[j], NULL, processDataThread,(void*) &ptr);
}
sleep(3); //sleep to let processthreads start up
pthread_create(&input_thread_id, NULL, inputThread,(void*) &ptr);
}
我确定入队和出队是正常的。我写了一个文件,并验证了我在inputThread中收到的所有内容是否已出队。将process_data()
函数放入代码中时出现问题。该函数将减慢processDataThread的速度,导致inputThread在processDataThread可以出队之前填充队列。这会导致丢失数据,因为inputThread的运行速度比processDataThread快。如果我注释掉`process_data()'函数,队列不会溢出。即使增加了processDataThreads的数量(我尝试过3、5和10)后,队列入队的速度仍然比出队的速度快。
运行时getData()
至dequeue()
为.01s,程序连续循环运行而无需队列填充getData()
到process_data()
的运行时间为0.05秒,几秒钟后队列已满。
我做错了什么?我认为增加processDataThread的数量将比出队更快地解决入队问题,但没有。
该函数将减慢processDataThread的速度,导致inputThread在processDataThread可以出队之前填满队列。
这很正常。线程完成的工作通常比这些线程的输入生成慢(这可能很简单,就像从文件中读取行一样)。请记住,我们使用线程来并行化缓慢的进程。
这将导致丢失数据
如果队列丢失数据,您的队列有问题!
我确定入队和出队工作正常。
否,丢失数据的队列无法正常工作。
您没有显示要按要求调试的代码,因此我们只能猜测问题所在。听起来您有一个固定大小的队列,并且enqueue
仅在队列已满时放弃将要添加到队列的项目。这是一个错误。
如果是问题,要么在队列已满时增大队列,要么阻塞直到有足够的空间来排队要排队的内容。 This working queue implementation执行后者。