0

我有两个函数,由两个 p 线程调用的生产者和消费者,但是函数中的 while 循环没有运行。它是一个linux RT系统。这是我的代码。我在eclipse中编码。

#include <stdio.h>
#include"NIDAQmx.h"
#include <pthread.h>
#include "sts_queue/s_q.c"
#include <stdlib.h>

void *producer(void *ptr);// first function
void *consumer(void *ptr);// second function

TaskHandle taskHandle = 0;
int ret = 0;
int numChannels = 0;
int numRead;
float64 data[100];
int iret1, iret2;
pthread_t thread1, thread2;

int main(void) {
char *message1 = "Producer ended";
char *message2 = "consumer ended";
    init();
ret = DAQmxCreateTask("task", &taskHandle);

ret=DAQmxCreateAIVoltageChan(taskHandle, "PXI1Slot2/ai0", "",
        DAQmx_Val_Cfg_Default, -5, 5, DAQmx_Val_Volts, NULL);

ret=DAQmxCfgSampClkTiming(taskHandle, "", 1000, DAQmx_Val_Rising,DAQmx_Val_ContSamps, 100);

ret=DAQmxGetTaskAttribute(taskHandle, DAQmx_Task_NumChans, &numChannels);


ret=DAQmxStartTask(taskHandle);

iret1 = pthread_create(&thread1, NULL, producer,(void*) message1);// calling two threads
iret2 = pthread_create(&thread2, NULL, consumer,(void*) message2);// calling thread



}

void *producer(void *ptr) // enque function
{
char *message;
int i = 0;
int ret;
message = (char *) ptr;
while(i<1000)
{
//ret=DAQmxReadAnalogF64(taskHandle, 100, 10.0, DAQmx_Val_GroupByChannel, data,100 * numChannels, &numRead, NULL);
printf("task handle=%d\n",taskHandle);
printf("value of i=%d\n",i);
printf("Number of sample read%d\n",numRead);
printf("ret%d\n",ret);
sleep(.1);
i++;
}
ret=DAQmxStopTask(taskHandle);

ret=DAQmxClearTask(taskHandle);

printf("%s \n", message);
pthread_join(thread1, NULL);
return 0;
}

void *consumer(void *ptr) // deque function
{
char *message;
int k = 0;
int elements=0;
message = (char *) ptr;
while(k<1000)
{

    printf("value ofk=%d\n",k);
    sleep(.1);
    k++;
}
printf("%s \n", message);
pthread_join(thread2, NULL);

 }

我应该使用 pthread_exit 还是 pthread-join?当while循环退出时如何使用pthead_exit退出第一个线程?

现在我的控制台打印了这个

task handle=-163491360
start0
value ofk=0
task handle=-163491360
value of i=0
Number of sample read0
ret0
logout

但实际上 i 和 k 的值应该达到 1000,当达到 1000 时,while 循环将停止并退出

有时我也会收到此错误

pure virtual method called
terminate called without an active exception
Aborted
logout
4

1 回答 1

0

创建thread1和thread2后pthread_join需要调用函数。main否则,主线程将在 thread1 和 thread2 完成之前终止。

于 2020-07-23T07:08:29.850 回答