我真的很难尝试使函数在 pthread 中循环。我的函数被这个 pthread 调用,它应该循环到无限,但是它只是没有发生。这就是我寻求帮助的原因。我使用以下代码创建了我的线程:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void *thread_s(void *params_s);
int main(int argc, char *argv[]) {
int s1_hand = 0;
pthread_t routines[1];
printf("Creating Thread -> Main Thread Extremely Busy!\n");
s1_hand = pthread_create(&(routines[0]), NULL, thread_s, (void *)&(routines[0]));
if (s1_hand != 0) {
printf("Not possible to create thread:[%s]\n", strerror(s1_hand));
exit(EXIT_FAILURE);
}
void* result;
if ((pthread_join(routines[0], &result)) == -1) {
perror("Cannot join S thread");
exit(EXIT_FAILURE);
}
pthread_exit(NULL);
return 0;
}
我希望连续运行的功能是:
void *thread_s(void *params_s) {
printf("Thread starting...\n");
int fd, chars, pars, c_1, f_parse, pripa = 1;
fd = open("/dev/ttyUSB0", O_RDONLY | O_NOCTTY | O_SYNC);
if (fd < 0){
perror("Unable to open the fildes!");
exit (EXIT_FAILURE);
}
FILE *stream_a, *stream_b;
stream_a = fdopen(fd, "r");
stream_b = fopen(FILE_II, "w+");
if (stream_a == NULL && stream_b == NULL){
perror("IMPOSSIBLE TO CREATE STREAMS");
exit(EXIT_FAILURE);
}
c_1 = fgetc(stream_a);
f_parse = lookatit(pripa, c_1, array);
printf("First Parse Done -> (%i)\n", f_parse);
while ((chars = fgetc(stream_a)) != EOF){
pars = lookatit(0, (uint8_t)chars, array);
if (pars == 1){
printf("MESSAGE FOUND AND SAVED -> (%i)\n", parsing);
fprintf(stream_b,"%.6f %.6f %.6f\n", array[0], array[1], array[2]);
} else{
printf("Looking for the Message: %i\n", parsing);
continue;
}
chars++;
}
fflush(stream_b);
fclose(stream_b);
fclose(stream_a);
close(fd);
pthread_exit(NULL);
return 0;
}
函数“lookatit”执行解析例程,当找到消息时返回 1,当未找到消息时返回 0。该函数在没有找到消息时完美循环,但是当它找到消息时,if 语句(第 22 行第二个代码)打印“MESSAGE FOUND AND SAVED”并立即终止程序。为什么我的程序会出现这种行为?